SarpSTA
SarpSTA

Reputation: 279

How to sum adjacent numbers of same sign using List.fold in F#

Let's say I have a list in F# like this: [5,-2, -6, 7, -2, 2, 14, 2]

I want to write a function that will use List.fold to return a new list such as [5, -8, 7, -2, 18]

My template looks like this:

let sumAdjacentOfSameSign (lst :int list) : int list =
    let f x y = 
    if x.Length = 0 then
        [y]
    elif System.Math.Sign(x) = System.Math.Sign(y) then ...
    else y :: x


    List.fold f [] lst

I need to fill in the ... part but can't quite say how.

Upvotes: 1

Views: 89

Answers (1)

Brian Berns
Brian Berns

Reputation: 17078

Making the fewest changes to your code, I would do this:

let sumAdjacentOfSameSign (lst :int list) : int list =
    let f (x : int list) (y : int) =
        if x.Length = 0 then
            [y]
        elif System.Math.Sign(x.Head) = System.Math.Sign(y) then
            (x.Head + y) :: x.Tail
        else y :: x

    List.fold f [] lst
        |> List.rev   // note that you have to reverse the resulting list

But I would suggest simplifying f to:

    let f (x : int list) (y : int) =
        match x with
            | head :: tail when
                System.Math.Sign(head) = System.Math.Sign(y) ->
                    (head + y) :: tail
            | _ -> y :: x

Upvotes: 1

Related Questions