Folding a list in F#

Posted by bytebuster on Stack Overflow See other posts from Stack Overflow or by bytebuster
Published on 2012-09-30T00:03:04Z Indexed on 2012/09/30 3:37 UTC
Read the original article Hit count: 122

Filed under:

I have a pretty trivial task but I can't figure out how to make the solution prettier.
The goal is taking a List and returning results, based on whether they passed a predicate. The results should be grouped. Here's a simplified example:

Predicate: isEven
Inp : [2; 4; 3; 7; 6; 10; 4; 5]
Out: [[^^^^]......[^^^^^^^^]..]

Here's the code I have so far:

let f p ls =
    List.foldBack
        (fun el (xs, ys) -> if p el then (el::xs, ys) else ([], xs::ys))
        ls ([], [])
    |> List.Cons // (1)
    |> List.filter (not << List.isEmpty) // (2)

let even x = x % 2 = 0

let ret =
    [2; 4; 3; 7; 6; 10; 4; 5]
    |> f even
// expected [[2; 4]; [6; 10; 4]]

This code does not seem to be readable that much. Also, I don't like lines (1) and (2). Is there any better solution?

© Stack Overflow or respective owner

Related posts about F#