Rus*_*tam 4 f# postfix-operator
在Perl语言中,人们可以写出类似的内容
someFunction() if $x == 0
Run Code Online (Sandbox Code Playgroud)
即在后缀表示法中应用条件.
我确信在F#中必须有类似的表达式,因为它在处理函数时非常灵活.但是当我试着写的时候
someFunction() if x = 0
Run Code Online (Sandbox Code Playgroud)
要么
someFunction() << if x = 0
Run Code Online (Sandbox Code Playgroud)
我收到了预期的错误消息.有没有办法在F#中实现更多或更少的通用后缀条件运算符?
没有内置的F#支持,所以我建议只使用普通的前缀样式条件(或模式匹配).在社区中也没有标准的操作员/功能,因此惯用的风格只会使用普通的if
.
我认为你能做的最好是这样的:
/// Evaluates lazy value only if the specified boolean holds
let assuming b (v:Lazy<_>) = if b then v.Value
// Print foo only when x > 40
let foo() = printfn "hi"
let x = 42
lazy foo() |> assuming (x > 40)
Run Code Online (Sandbox Code Playgroud)
请注意,我必须添加lazy
到表达式(以确保在条件不成立时实际上不会对其进行求值).这是有效的,但它肯定比写作if x>40 then foo()
更丑陋- 但试验是一件有趣的事情:-)
归档时间: |
|
查看次数: |
420 次 |
最近记录: |