Reputation: 31
A) Write the function indefIntegratePoly
which takes a list of coefficients standing for a polynomial (in the order from highest degree to lowest with all terms present) and returns a new list of coefficients standing for an indefinite integral of that polynomial. You must use foldr
(Given below). Assume the constant produced for the anti-derivative representing the indefinite integral is 0.0.
fun foldr (f, s, []) = s
| foldr (f, s, x::rest) = f(x, foldr(f, s, rest));
I just want to know where to start, cause I’m struggling to get ant type of function that makes sense.
Upvotes: 0
Views: 260
Reputation: 16105
fun foldr (f, s, []) = ...
The built-in foldr
resembles this function, but is defined as
fun foldr f s [] = ...
That is, curried rather than tupled.
I'll assume your version of foldr
in the below response.
I just want to know where to start
You could start with
fun indefIntegratePoly ks =
let fun f (k, acc) = ...
in foldr (f, [], ks)
end
where f
takes a single coefficient and builds a list of integrated coefficients in acc
.
Note that foldr
folds from the right to the left, so the first value of k
is the coefficient for the term with the smallest power. You know how large that power is, since it starts with being 1, and subsequent iterations of the fold represent terms with a power more than that.
If I recall right, a·x^n integrates to (a·x^(n+1))/n, so for any one term, you must divide by the term's power. This means that the context of f
must have that available. acc
can be any type, e.g. int × int list, where the first int is the current term's power.
Expanding on the template,
fun indefIntegratePoly ks =
let fun f (k, (n, iks)) =
(n+1, ...)
in #2 (foldr (f, [], (1, ks)))
end
the fold accumulates a pair where k
is the coefficient for the current term, n
is the power of the current term, and iks
is a list of integrated coefficients. Increasing the power of each term (turning the n into n+1 in a·x^n → (a·x^(n+1))/n) is a matter of adding an extra term to the list, which can be accomplished by initializing the fold with some [j]
instead of []
, where j
is the coefficient for the constant term k as k → k·x^1.
Since foldr
now produces a pair, and the #1
part of this pair is only used during the iteration, while the #2
part holds the integrated coefficients, the largest power can be discarded by destructuring the pair using #2
.
Upvotes: 0