将具有区别联合类型的列表过滤到单个类型

时间:2013-09-11 19:51:28

标签: f#

给定类型

type C = Circle of int | Rectangle of int * int

和一个集合

let l = [ Circle(1); Circle(2); Rectangle(1,2)]

我只想处理圈子

 let circles = l |> List.filter(fun x-> match x with 
                                        | Circle(l) -> true
                                        | _ -> false)

但是我的圈子仍然是C型,因此我无法做到

for x in circles do
  printf "circle %d" x.??

我必须做

for x in circles do
  match x with 
  | Circle(l) -> printf "circle %d" l
  | _ -> ())

似乎错了..

2 个答案:

答案 0 :(得分:30)

使用List.choose - 就像List.filterList.map一样。

let circles =
    l |> List.choose(fun x ->
        match x with 
        | Circle l -> Some l
        | _ -> None)

for x in circles do
  printf "circle %d" x

答案 1 :(得分:3)

l|>Seq.iter (function |Circle l->printf "circle %d" l|_->())