您好我必须使用列表进行锻炼。我有一个用列表代码检查算术:
let rec q3 lista r =
match lista with
| [] -> false
| [x] -> true
| x1::x2::xs -> if r = x2 - x1 then (q3 xs r) else false
q3 [2;4;6] 2;;
但在此之后,我有问题。我必须在最后一个负数后计算列表中数字的总和 或者如果我的名单中只有正数,则为所有人。
这是总和的代码。这很简单,但如何做到这一点:(我在f#编程中很新:P有什么想法吗?
我有这样的例子列表:
let lists = [4;-3;1;9]
// sum =10
//calculate
let rec sum values =
match values with
| [] -> 0
| head::tail -> head + sum(tail)
//test
let x = sum lists
答案 0 :(得分:1)
我猜你正在学习F#,所以我不会展示完整的答案(那时你不会学到太多东西)。
您想要在最后一个负数之后对列表中的所有数字求和。另一种看待这种情况的方法是,当你走过列表时,每次找到负数时都要重新开始计数(从零开始)。
这对你的sum
版本来说并不容易,但你可以重写sum
函数来使用accumulator参数(它保留到目前为止的数字总和):
let rec sumAcc acc values =
match values with
| [] ->
// return the sum of values in the list so far
| head::tail ->
// add the value in the 'head' to the sum so far
// and call 'sumAcc' recursively on the rest of the list
let sum values = sumAcc 0 values
现在,您可以非常轻松地解决问题 - 因为当head
为负数时,您可以在累加器参数中重置“目前为止的总和”。所以,你只需要添加另一个案例:
| head::tail when head < 0 ->
// Ignore the sum so far and call 'sumAcc' on the rest of the list
答案 1 :(得分:0)
let rec sumList acc lst =
match lst with
| [] -> acc
| hd::tl -> hd + sumList acc tl
|hd::tl when hd < 0 -> sumList acc lst
let sum lst = sumList 0 lst ;;
sum [1;2;-5] ;;
不知道如何在列表的其余部分以递归方式执行此操作 subList acc lst是错误的:D因为仍然得到-2值:D