13

Given a type

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

and a collection

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

I want to handle only circles

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

But my circles are still of type C, thus I cannot do

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

I have to do

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

seems wrong..

4

2 回答 2

32

使用——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
于 2013-09-11T20:01:48.880 回答
3
l|>Seq.iter (function |Circle l->printf "circle %d" l|_->())
于 2013-09-12T08:50:34.463 回答