Свя*_*лав 0 f# casting pattern-matching seq
let a = seq { yield Some 1; yield Some 2; yield Some 3; yield None }
a
|> Seq.takeWhile Option.isSome // cast 1
|> Seq.map Option.get // cast 2
|> Seq.iter (printfn "%A")
Run Code Online (Sandbox Code Playgroud)
a
|> Seq.filter Option.isSome // cast 1
|> Seq.map Option.get // cast 2
|> Seq.iter (printfn "%A")
Run Code Online (Sandbox Code Playgroud)
type AB =
| A of a : int
| B of b : string
let a = seq{
yield A 1
yield A 2
yield B "ds"
yield B "fsdf"
}
let (|As|Bs|) = function
| A _ -> As
| B _ -> Bs
let matcher = function
| A a-> printfn "%A" a
| B b -> printfn "%A" b
a
|> Seq.groupBy (|As|Bs|) // cast 1
|> Seq.map snd
|> Seq.iter (Seq.iter matcher) // cast 2
Run Code Online (Sandbox Code Playgroud)
对于“案例2”,您可以使用Seq.choose
身份功能id
:
a
|> Seq.choose id
|> Seq.iter (printfn "%A")
Run Code Online (Sandbox Code Playgroud)
该文档的Seq.choose
说
将给定函数应用于列表的每个元素,并返回由每个元素的结果组成的列表,其中函数返回带有某些值的Some。
传递给它的身份函数将因此返回Option
is 的每个值的内容Some
。