Partial sum in Standard ML?

落爺英雄遲暮 提交于 2019-12-20 05:39:18

问题


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 in function psum2[L] i dont know how to go through each value and add them up so I just print the list.

fun psum2(L) : int list = 
   if L=nil then []
   else L;

fun pSum(L) : int list = 
   psum2(L);

exception Empty_List;

psum([2,3,4]);

回答1:


Your question is a little broad, but here's one way to sum a list. Perhaps you can adapt it to your purposes:

fun sum [] = 0
  | sum (h::t) = h + sum t


来源:https://stackoverflow.com/questions/14388412/partial-sum-in-standard-ml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!