Storm
Storm

Reputation: 3242

Getting list of values from list of options

I have a simple list of string options, like this:

let myList = [ None; Some "foo"; Some "bar" ]

I tried to get the non-empty values from the list using this approach:

myList
|> List.filter Option.isSome
|> List.map Option.get

But then I found another code somewhere on the Internet:

myList
|> List.choose id

They both do the exact same thing. Are there any performance differences between those two code samples? Or is it just about code preference?

Upvotes: 1

Views: 173

Answers (1)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236218

Your first code (filter + map) does this:

  1. (Recursively) loop through myList applying Option.isSome function (pattern matching happens here) to each item and building a new list of items where function returned true

    [Some "foo"; Some "bar"]

  2. (Recursively) loop through the new list applying Option.get function (also pattern matching) to each item and building yet another new list of values returned from the function

    ["foo"; "bar"]

The second approach (choose) does this:

  1. (Recursively) loop through myList applying id function to each item and building a new list of items where function retuned Some (only one pattern matching)

So it's twice less job done and much less code to write and maintain.

choose is an idiomatic way to 'unwrap' options skipping those which None. That's why it exists in all collection modules.

Upvotes: 3

Related Questions