SML finding a sum of squares/halves using other functions

658 Views Asked by At

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!

1

There are 1 best solutions below

0
On

Here is a possible solution:

fun sumF f 0 = 0
  | sumF f n = f n + sumF f (n - 1)

Your problem is, that you don't actually use the inc function in the definition of sumF function. You define the sumF function with only one argument of type int, but then you call this function with "two arguments". Your function call sumF inc 3 is interpreted as ((sumF inc) 3), and since the type of inc 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 call sumF n in the definition of sumF n.

You can call the function above as

- fun inc x = x + 1;
val inc = fn : int -> int
- sumF inc 3;
val it = 9 : int

or a bit shorter with anonymous function:

- sumF (fn x => x + 1) 3;
val it = 9 : int

Regards, Špela