0

Possible Duplicate:
Partial sum in Standard ML?

Im new to functional programming and I have an assignment to compute partial sum of a list. E.g. - psum [1,1,1,1,1]; val it = [1,2,3,4,5] : int list

Here is the my code so far. However my function just returns the list as it is.

 fun ppsum2([])=[]
| ppsum2(x::L) = x::ppsum2(L);


 exception Empty_List;

fun psum(L) : int list = 
if L=nil then raise Empty_List
else psum2(L);


psum([2,3,4]);  
2
  • 1
    Surely your code is indented like that? :( Anyway, consider [] -> [] to avoid exceptions entirely. Then, consider the base case and the termination case for the recursive function, and what the result for each step should be, given the input.
    – user166390
    Jan 17 '13 at 23:12
  • 1
    You say "sum", but you haven't used + at all. Try evaluating ppsum2 [2,3,4] by hand on paper and you'll see why you get an identical list back.
    – molbdnilo
    Jan 18 '13 at 10:48
1

Since this looks like homework, I hope this is simple enough:

 fun psum2 [] total = []  
   | psum2 (h::t) total = (total+h) :: psum2 t (total+h)

 fun psum lst = psum2 lst 0
1

You could look up the source code for Haskells scanl1 function, and translate it to ML.

This way, you do not learn functional programming, but media competence.

Not the answer you're looking for? Browse other questions tagged or ask your own question.