I need to get the subset of a list from the first occurrence of an element in F#. I have implemented this using a simple recursive routine as follows:
// Returns a subset of a list from the first occurrence of a given item
// e.g. ignoreUpTo "B" ["A";"B";"C";"D"] yields ["C"; "D"]
let rec ignoreUpTo item l =
match l with
| hd::tl -> if hd = item then tl else ignoreUpTo item tl
| _ -> []
This works for my needs, but I was wondering if there is a better way to do this using the existing List functions in the F# language.
If you're using F# 4, there's now a List.skipWhile function; before F# 4, the skipWhile function was only available on seqs. So you could write:
let ignoreUpTo item l =
l
|> List.skipWhile ((<>) item)
|> List.skip 1 // Because otherwise you'll get ["B"; "C"; "D"]
If you're using F# 3.1 or earlier, you'll need to turn your list into a seq first:
let ignoreUpTo item l =
l
|> List.toSeq
|> Seq.skipWhile ((<>) item)
|> Seq.skip 1 // Because otherwise you'll get ["B"; "C"; "D"]
|> Seq.toList // Optional, if you can get by with a seq instead of a list
You can implement it using List.skipWhile. I assume that you want to return empty list if none of the elements of the list l equal item.
let ignoreUpTo item l =
match List.skipWhile ((<>) item) l with
| [] -> []
| x :: xs -> xs
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With