在F#中拔出一个歧视的工会案例?

时间:2018-12-17 11:15:14

标签: f# discriminated-union

假设我有一个类似DU的人:

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

然后我有一个类似的收藏集:

fruits : Fruit list

我想提取所有Apple实例以执行一些计算:

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

我的问题是:是否有更简洁的方式编写此代码?

类似:

// Not real code
let apples = 
  fruits
  |> Seq.match Apple

2 个答案:

答案 0 :(得分:3)

确实不多。尽可能简洁:

let apples = 
  fruits
  |> Seq.choose (function Apple(a,b) -> Some(a,b) |_-> None)

答案 1 :(得分:0)

可能更简洁一些;您不必使用Seq.choose:

<%= simple_form_for @movie do |f| %>
  <%= select_tag(:category_id, options_for_select(@categories), prompt: "Select a Category") %>
  <%= f.input :name %>
  <%= f.input :director %>
  <%= f.input :description %>
  <%= f.button :submit %>
<% end %>

如果需要更多地方,请将lambda提取到辅助函数中

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