标准机器学习中的部分总和?

问题描述 投票:0回答:2

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

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

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]);
list functional-programming sum partial sml
2个回答
1
投票

您的问题有点宽泛,但这是总结列表的一种方法。也许您可以根据您的目的进行调整:

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

0
投票

这在 Haskell 等语言中称为 scanl,这是 scanl 和 scanl1 的一种实现:

fun scanl f q ls =
let fun aux f q ls = q :: (case ls of
               [] => []
             | (x::xs) => aux f (f(q,x)) xs)
in
aux f q ls
end

fun scanl1 _ [] = []
  | scanl1 f (x::xs) = scanl f x xs

使用示例:

scanl op+ 0 [1,2,3];
scanl1 op+ [1,2,3];
© www.soinside.com 2019 - 2024. All rights reserved.