This is from a teaching example to illustrate CPS and tail recursion:
fun sum [] k = k 0
| sum (x::xs) k = sum xs (fn y=>k(x+y));
I have problems understanding how the anonymous function fn y=>k(x+y) would sum up the elements of the input list correctly.
From what I understand, that anonymous function means a new function with one argument y where the function body calls the original function k with argument y+x.
If I invoke sum [1,2,3,4,5] (fn x=>x); I get 15. If I have sum [1,2,3,4,5] (fn x=>3x); the answer is 45. The user of the sum function hence would have to first understand the exact gory details of sum as only an appropriate version of k will produce the sum of the given list. What is the real-world purpose of having a user supplied function in such a manner?
If I am the writer of the sum function, I cannot control what the user will pass in for k. In other words, how do I even specify what the function would do precisely?
kis and that to get the correct result as per the function contract they must pass an identity function. The "proper" solution would not exposekparameter in thesumsignature at all. - zerkms