给定类型
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
| _ -> ())
似乎错了..
答案 0 :(得分:30)
使用List.choose
- 就像List.filter
和List.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|_->())