0

Suppose I have a DU like:

type Fruit = 
| Apple of string * bool
| Banana of string
| Cherry of string

Then I have a collection like this:

fruits : Fruit list

I want to pull out all of the Apple instances to perform some computation:

// apples is Seq<string * bool> 
let apples = 
  fruits
  |> Seq.choose (fun x -> 
    match x with 
    | Apple a -> Some a
    | _ -> None
  )

My question is: is there a more concise way to write this?

Something like:

// Not real code
let apples = 
  fruits
  |> Seq.match Apple
sdgfsdh
  • 24,047
  • 15
  • 89
  • 182

2 Answers2

3

Not much really. This is as concise as you can get:

let apples = 
  fruits
  |> Seq.choose (function Apple(a,b) -> Some(a,b) |_-> None)
AMieres
  • 4,547
  • 1
  • 10
  • 15
0

Slightly more concise is possible; you don't have to use Seq.choose:

let apples = fruits |> List.filter (fun fruit -> match fruit with Apple _ -> true | _ -> false)

If you need this in more places, extract the lambda into a helper function

let isApple = function | Apple _ -> true | _ -> false
nilekirk
  • 2,190
  • 1
  • 8
  • 9