Click here to Skip to main content
15,881,281 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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 ?


F#
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] ;;
Posted
Updated 11-Nov-14 3:11am
v2
Comments
Enrique A. Casanovas Pedre 11-Dec-14 17:58pm    
It looks like a school assignment.

1 solution

The sum of all positive numbers after the last non-negative can be calculated like this:
F#
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 reverses the list then Seq.takeWhile will take numbers while the function
F#
fun x -> x > 0
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:

F#
let lst = [-5; 4; -3; 2; 6; 10]
let afterLastNegative =
    lst
    |> List.rev
    |> Seq.takeWhile ((<) 0)
    |> Seq.sum
printfn "%A" afterLastNegative


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.
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900