I have written a function sumF in SML that does the following:
fun inc x = x+1;
val inc = fn : int -> int
sumF inc 3;
9 : int (i.e. inc 3+inc 2+ inc 1+ 0)
sumF
fun sumF f 0 = 0 |
sumF f n = f n + sumF f (n-1);
Now I want to write a function sumsq (Sum of squares) using sumF and I am not able to do that. Here's what I did.
fun sumsq 0 = 0 |
sumsq n = n*n + sumsq (n-1);
val sumsq = fn : int -> int
sumsq 3;
val it = 14 : int
This is the code that is not giving me the desired output:
fun sumF f 0 = 0 |
sumF f n = f n*n + sumF f (n-1);
val sumF = fn : (int -> int) -> int -> int
sumF sumsq 3;
val it = 53 : int // wrong output
Your sumsq
function already delivers the sum of squares, but it's not defined in terms of sumF
. Your latter code isn't what is asked in this (I assume) homework question, and it doesn't make sense, because it now computes the sum of sum of squares or something like that.
What you want is something like this:
fun sumsq n = sumF ? n
I leave it to you to figure out what to fill in in place of the ?
.