标准 ML 中的部分总和? [英] Partial sum in Standard ML?

查看:16
本文介绍了标准 ML 中的部分总和?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是函数式编程的新手,我的任务是计算列表的部分总和.例如.- psum [1,1,1,1,1];val it = [1,2,3,4,5] : int 列表

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

到目前为止,这是我的代码.但是在函数 psum2[L] 中,我不知道如何遍历每个值并将它们相加,所以我只打印列表.

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]);

推荐答案

您的问题有点宽泛,但这里有一种汇总列表的方法.也许您可以根据自己的目的调整它:

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

这篇关于标准 ML 中的部分总和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆