Trident D'Gao
Trident D'Gao

Reputation: 19690

How can I extract x values from Some(x) values from a sequence of Option 'a?

This one seems to be a brainer to me. I need to extract x values wrapped into Some(x) from the sequence. I can do it with

xs |> Seq.fold (fun state x -> match x with -> | Some(y) -> y::state | None -> state) [] 
    |> Seq.toList 
    |> List.rev 
    |> List.toSeq

Is there a nicer way?

Upvotes: 1

Views: 1138

Answers (2)

Joel Mueller
Joel Mueller

Reputation: 28745

For a discriminated union that isn't actually the standard Option type, you just need to supply a function to Seq.choose that takes an instance of your discriminated union and maps it to a standard Option. Something like...

xs |> Seq.choose (function Nothing _ -> None | Something x -> Some x)

Upvotes: 5

John Palmer
John Palmer

Reputation: 25516

This is quite simple

xs |> Seq.choose id

Upvotes: 5

Related Questions