1

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

1 Answer 1

1

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 ?.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the help sir, a small doubt - should I be using the concept of partial application here? @AndreasRossberg
@rm4596, sure, you can if you prefer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.