casting - F#如何避免两次施法
问题描述
情况1
- 取元素 while is Some value from sequense
- 打印一些值
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")
案例2
- 过滤一些值的序列
- 打印 Some 的值
a
|> Seq.filter Option.isSome // cast 1
|> Seq.map Option.get // cast 2
|> Seq.iter (printfn "%A")
案例3
- 按类型按元素分组
- 打印每组的值
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
为什么我需要避免双重铸造?
- 保持代码更干净
- 避免抛出异常
解决方案
对于“案例 2”,您可以使用Seq.choose
身份功能,id
:
a
|> Seq.choose id
|> Seq.iter (printfn "%A")
文档Seq.choose
说_ _
将给定函数应用于列表的每个元素,并返回包含每个元素的结果的列表,其中函数返回 Some 和一些值。
因此,将标识函数传递给它将返回每个Option
值的内容Some
。
推荐阅读
- javascript - 从一页到另一页的平滑滚动 URL 问题
- php - 将 file_get_contents 作为整数存储到会话中的问题
- python - 无法按照文章中的说明加载数据集
- pytorch - 在pytorch中,如何用另一个张量填充一个张量?
- javascript - 向php发送ajax请求时没有数据响应
- python - Selenium 预期条件 - 等待 xpath 可用 - 我不知道如何在我的代码中键入它
- windows - 错误:browser_process_sub_thread.cc(221)] 在 Windows 上使用 Selenium ChromeDriver 和 Chrome 等待网络服务 57 毫秒
- c - 我正在尝试使用 c 中的函数编写华氏到摄氏度的代码
- css - 无法调整 mat-tree 中列表项的行高
- javascript - array.concat() 的问题