So I want to find the sum of applying function f to the first n integers, when the sum of applying f to the first n integers is f applied to n plus the sum of applying f to the first n-1 integers, as in:
- fun inc x = x+1;
> val inc = fn : inet -> int
- sumF inc 3;
> 9 : int i.e. inc 3+inc 2+ inc 1+ 0
and my sumF looks like this now:
- fun sumF 0 = 0 | sumF n = sumF(n) + sumF(n-1);
val sumF = fn : int -> int
- sumF inc 3;
stdIn:15.1-15.11 Error: operator and operand don't agree [tycon mismatch]
operator domain: int
operand: int -> int
in expression:
sumF inc
As you can see I get an error, so maybe anyone knows how to fix it? Because later on, I want to write sumSq (sumSq n = (nn) + sumSq(n-1)) and sumHalf (sumSq n = (nn) + sumSq(n-1)), using sumF. Thanks!
Here is a possible solution:
Your problem is, that you don't actually use the
inc
function in the definition ofsumF
function. You define thesumF
function with only one argument of type int, but then you call this function with "two arguments". Your function callsumF inc 3
is interpreted as((sumF inc) 3)
, and since the type ofinc
is int -> int, but the function expects the argument of type int, you get the error. And, besides this, your function has an additional problem - it creates infinite loop, since you callsumF n
in the definition ofsumF n
.You can call the function above as
or a bit shorter with anonymous function:
Regards, Špela