wolf
wolf

Reputation: 419

F# How to get value of Some from a list

I have a list of options such as [Some 1; Some 2]. My aim is to get the values of Some elements without using pattern matching and options.get functions.

I have a testfunction which returns ('a -> 'b) option -> 'a option -> 'b option. To achieve my goal, how can i use this function?

let test xa xb = 
  match xa with
  | None -> None
  | Some el -> Option.map el xa

Upvotes: 2

Views: 2132

Answers (1)

Fyodor Soikin
Fyodor Soikin

Reputation: 80744

You can get the values of the Some elements with the List.choose function, which does almost exactly that.

[Some 1; Some 2] |> List.choose id
// Returns [1; 2]

The semantics of the List.choose function is that it lets you chose some elements of the list by providing a function, which for every element returns either Some or None. Elements for which the function returns None are discarded, and the Some results are unwrapped and returned as a list. You can think of this function as a combination of map and filter in one.

Because the elements of your list are already of the option type, your choosing function would be id, which is a standard library function that simply returns its argument unchanged.

Upvotes: 3

Related Questions