是“可选"的管道操作员惯用的F# [英] is an "optionalized" pipe operator idiomatic F#
问题描述
我很喜欢使用管道运算符'|>'.但是,当将返回简单"值的函数与返回"Option-Typed-values"的函数混合时,情况会变得有些混乱,例如:
I like to use the pipe operator '|>' a lot. However, when mixing functions that return 'simple' values with functions that return 'Option-Typed-values', things become a bit messy e.g.:
// foo: int -> int*int
// bar: int*int -> bool
let f (x: string) = x |> int |> foo |> bar
可行,但可能会抛出'System.FormatException:...'
works, but it might throw a 'System.FormatException:...'
现在假设我想通过使函数'int'提供可选结果来解决此问题:
Now assume I want to fix that by making the function 'int' give an optional result:
let intOption x =
match System.Int32.TryParse x with
| (true, x) -> Some x
| (false,_) -> None
现在唯一的问题就是函数
Only problem now is that of course the function
let g x = x |> intOption |> foo |> bar
由于输入错误而无法编译.好的,只需定义一个可选"管道:
won't compile due to typing errors. Ok, simply define an 'optionalized' pipe:
let ( |= ) x f =
match x with
| Some y -> Some (f y)
| None -> None
现在我可以简单地定义:
now I can simply define:
let f x = x |> intOption |= foo |= bar
一切都像个魔术.
好,问题:那是惯用的F#吗?可以接受吗风格不好?
备注:当然,给定正确的类型,'| ='运算符允许随意拆分和合并带有选项的管道",而仅在意重要的选项:
Remark: Of course, given the right types the '|=' operator allows to split and merge 'pipelines' with options at will while only care about options where they matter:
x |> ...|> divisionOption |= (fun y -> y*y) |=...|>...
推荐答案
我认为使用Option.map会更惯用:
I think using Option.map would be more idiomatic:
让g x = x |> intOption |> Option.map foo |> Option.map栏
let g x = x |> intOption |> Option.map foo |> Option.map bar
这篇关于是“可选"的管道操作员惯用的F#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!