Hi,
For a functional programming course I am taking, I am practicing
defining new datatypes with SML. In particular, I defined a
multidimensional array type:
datatype 'a array = Array of (int * 'a list);
where the int represents the dimension of the outermost array. Examples:
val vector = Array(3, [1,2,3]);
val matrix = Array(3,
[Array(3, [1, 2, 3]),
Array(3, [4, 5, 6]),
Array(3, [7, 8, 9])] )
val cub = Array(2,
[Array(3,
[Array(3,
[Array(3, [1, 2, 3]), Array(3, [4, 5, 6]),
Array(3, [7, 8, 9])]),
Array(3,
[Array(3, [1, 2, 3]), Array(3, [4, 5, 6]),
Array(3, [7, 8, 9])]),
Array(3,
[Array(3, [1, 2, 3]), Array(3, [4, 5, 6]),
Array(3, [7, 8, 9])])]),
Array(3,
[Array(3,
[Array(3, [1, 2, 3]), Array(3, [4, 5, 6]),
Array(3, [7, 8, 9])]),
Array(3,
[Array(3, [1, 2, 3]), Array(3, [4, 5, 6]),
Array(3, [7, 8, 9])]),
Array(3,
[Array(3, [1, 2, 3]), Array(3, [4, 5, 6]),
Array(3, [7, 8, 9])])])])
matrix is a 3x3 array, and cube is a 2x3x3x3 array
I wanted to create a function that will return the element of the array
indexed by an int list. For example, for vector, index [2] means get
the 2nd element; for matrix, index [2,3] means get the element in the
2nd row and 3rd column. Etc...
So in an attempt to create such a function, I started off small to try
and create a function to index into a 2-D array:
fun matrixidx(i::nil, Array(d,a)) =
if i = 1 then
hd(a)
else
matrixidx([i], Array(d,tl(a)) )
| matrixidx(i::ls, Array(d,a)) =
if i = 1 then
matrixidx(ls, hd(a))
else
matrixidx((i-1)::ls, Array(d,tl(a)) );
But I get the following error:
! Toplevel input:
! matrixidx(ls, hd(a))
! ^
! Type clash: expression of type
! 'a list
! cannot have type
! 'a array/4 list
! because of circularity
I've been spending hours on this and tried many different variations in
defining matrixidx, but no-go. I am very confused and do not know what
the problem is, or even how to fix it. Thanks!
--john


|