f#列出负数的总和 [英] f# list sum with negative numbers
问题描述
我认为我为我的问题做了正确的解决方案,但我错了。
我必须在最后一个负数之后计算列表中每个元素的总和或者如果<列表中的
我对所有元素只有正的claculate总和。
代码我做了什么:不幸的是我必须这样做而不会使用只有高阶函数和列表模块。任何提示如何做到这一点甚至如何使用这个recusrion?
I thought that i made right solutiuon for my problem but i was wrong.
I must calculate sum of every elements in list after last negative number or if
in the list i have only positive claculate sum for all elements.
code what i have done : Unfortunalety i must do it without recusion using only high order function and list module. Any hints how to do that or even how to make it with this recusrion ?
let rec sumList acc lst =
match lst with
| [] -> acc
| hd::tl -> hd + sumList acc tl
|hd::_ when hd < 0 -> sumList acc lst
let sum lst = sumList 0 lst ;;
sum [1;2;-5] ;;
推荐答案
最后一次非负数之后的所有正数的总和可以这样计算:
The sum of all positive numbers after the last non-negative can be calculated like this:
let lst = [-5; 4; -3; 2; 6; 10]
let afterLastNegative =
lst
|> List.rev
|> Seq.takeWhile (fun x -> x > 0)
|> Seq.sum
printfn "%A" afterLastNegative
List.rev反转列表然后Seq.takeWhile将获取数字,而函数
List.rev reverses the list then Seq.takeWhile will take numbers while the function
fun x -> x > 0
为true,如果x为正,则返回true。然后Seq.sum简单地将所有数字相加。一个稍微短的版本将是:
is true, and it returns true if x is positive. Then Seq.sum simply sums all the numbers taken. A slighly shorter version would be:
let lst = [-5; 4; -3; 2; 6; 10]
let afterLastNegative =
lst
|> List.rev
|> Seq.takeWhile ((<) 0)
|> Seq.sum
printfn "%A" afterLastNegative
完全一样。 (<)是函数运算符的名称,并且部分应用了一个运算符,而另一个运算符由Seq.takeWhile函数提供。
It does exactly the same. (<) is the name of the function operator lesser than and is partially applied with one operator, leaving the other to be supplied by the Seq.takeWhile function.
这篇关于f#列出负数的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!