Reputation: 3242
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
Reputation: 236218
Your first code (filter + map) does this:
(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"]
(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:
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