This is for a class assignment.
I am to implement a function in ML evalxy poly x y
where poly
is an int list list
that represents a polynomial. A term at position n
in its inner list and position m
in the outer list is the coefficient for x^n * y^m
. For example, the list [[1],[0,~2,0,0,3],[],[],[],[],[~5,0,7]]
represents the polynomial 1 - 2x + 3 * x^4 * y - 5 * y^6 + 7 * x^2 * y^6
.
The function evalxy
is to evaluate the given polynomial using the given values for x and y. The type of the function is to be val evalxy = fn : int list list -> int -> int -> int
. An example is evalxy [[1],[0,~2,0,0,3],[],[],[],[],[~5,0,7]] ~1 1 = 8
.
I'm not allowed to define any other top-level functions, I'm not allowed to use a let-expression, and I'm not allowed to use recursion except for map
, foldr
, and foldl
. Those are also the only built-in functions I'm allowed to use.
I figure that I could do this by calling map
on the outer list, calling map
on each inner list, and for each inner list item I multiply the entry (the coefficient) by x and y. If I initialized the x and y counters to 1 each, then for the first entry (e.g. coefficients 0 and 0) then coefficient * 1 * 1 will return the coefficient, which is the expected value for exponents of 0. Then for each iteration of the outer list I could increment the y counter by the result of multiplying the counter by the provided y-value. For example, 1 * y = y
(for y^1, since it's initialized to 1), y * y
(for y^2). The same could be done for the x counter and the inner lists.
I realize that's not terribly clear. What I'm getting at is, for the first iterations of the outer list, some y counter (say, ycounter
) has the value:
- First iteration:
1
- Second iteration:
1 * y
- Third iteration:
1 * y * y
- and so on
The problem is, I don't know how I could maintain such a counter. Am I completely on the wrong track here? Any help is appreciated.