Thomas
Thomas

Reputation: 12107

Go through a list until some condition is met, in F#

let's take this data:

let a = [10; 11; 12; 13; 14; 0; 15; 16]

I'm trying to do this:

[
    let mutable skip = false
    for i in 0 .. a.Length - 1 do
        if a.[i] = 0 then skip <- true
        if not skip then yield a.[i]
]

but I was wondering if List.unfold could be used for this? (and how?)

In practice, I'm getting a sequence of sequences (seq of rows, each holding a seq of columns, from an Excel file), and I want to stop the parsing when I encounter an empty line, but the simplified example illustrates it.

The expression above works, so this is about me learning if unfold could be applied to this.

Upvotes: 1

Views: 357

Answers (2)

Nghia Bui
Nghia Bui

Reputation: 3784

Yes, you can use List.unfold:

let a = [10; 11; 12; 13; 14; 0; 15; 16]
a
|> List.unfold (function
    | [] -> None
    | x :: rest -> if x = 0 then None else Some (x, rest)
)

Upvotes: 0

FRocha
FRocha

Reputation: 960

I would use takeWhile:

let a = [10; 11; 12; 13; 14; 0; 15; 16]
Seq.takeWhile ((<>) 0) a
// |>  do your parsing

Upvotes: 4

Related Questions