Array in Haskell defined with type (not data) -
type array = int -> emptyarray :: array emptyarray = error ("access non-initialized index " ++ show i) putindex :: array -> int -> -> array putindex ar v = ar' ar' j | j==i = v | otherwise = ar j getindex :: array -> int -> getindex = (a i)
i don't understand emptyarray
, putindex
function. problems are:
- what type of ar'
- when ar' pattern match?
- when
j==i
?v
of typea
or? in case not return array.
- what happens in otherwise = ar j
- why
getindex (putindex emptyarray 1 3) 2
generate errorgetindex (putindex emptyarray 1 3) 1
returning 3 seems clear.
instead of answering of questions directly, i'll try give explanation rationale behind array a
type here.
arrays can thought of data structure has particular properties, namely given index can return value associated index. means can characterize array describing values associated particular indexes, , sounds function mapping input (the index) output (the value @ index). hence, array can thought of no different function, provided don't want know length or indices valid. rather limiting definition of array, learning exercise it's important see how data structures can turned functions considering important operations are.
what type of
ar'
look @ type signature:
putindex :: array -> int -> -> array putindex ar v = ar'
so ar :: array a
, i :: int
, v
:: a, and
ar' :: array a`.
when
ar'
pattern match?
i assume mean when definition of ar'
used. ar'
array a
, means it's function int -> a
. means gets used whenever getindex
called on it.
when
j == i
?v
type ofa
? in case not return array
look @ definition of putindex
. ar'
return value of putindex
, not v
. v
return value of ar'
when j == i
. v
has type a
, can tell type signature of putindex
. putindex
function augments existing function ar
, adding check first when i == j
.
what happens in
otherwise = ar j
if j /= i
, instead of returning v
(the new value being associated index i
), looks value @ index j
in original ar
. might more stated as
putindex originalarray indextoset newvalue = newarray newarray j | j == indextoset = newvalue | otherwise = getindex originalarray j
why
getindex (putindex emptyarray 1 3) 2
generate error?
essentially, can turn index lookup bunch of nested if statements:
putindex emptyarray i0 x0 ==> \i -> if == i0 x0 else emptyarray putindex ( putindex emptyarray i0 x0 ) i1 x1 ==> \i -> if == i1 x1 else if == i0 x0 else emptyarray putindex ( putindex ( putindex emptyarray i0 x0 ) i1 x1 ) i2 x2 ==> \i -> if == i2 x2 else if == i1 x1 else if == i0 x0 else emptyarray
and on, adding new layer of if-then-else
every new putindex
. specific example
putindex emptyarray 1 3 ==> \i -> if == 1 3 else emptyarray
then
getindex (putindex emptyarray 1 3) 2
is equivalent expression
if 2 == 1 3 else emptyarray 2
Comments
Post a Comment