【问题标题】:Not Function And Function Composition in F#F#中的非函数和函数组合
【发布时间】:2015-04-09 20:20:23
【问题描述】:
F# 是否有可能在 Operators.Not 和一些标准 .NET 函数(例如 String.IsNullOrEmpty)之间进行函数组合?
换句话说,为什么下面的 lambda 表达式是不可接受的:
(fun x -> not >> String.IsNullOrEmpty)
【问题讨论】:
标签:
function
lambda
f#
functional-programming
function-composition
【解决方案1】:
>> 函数组合反过来工作——它将左边函数的结果传递给右边的函数——所以你的 sn-p 将 bool 传递给 IsNullOrEmpty,这是一个类型错误。以下作品:
(fun x -> String.IsNullOrEmpty >> not)
或者你可以使用反向函数组合(但我认为>>在F#中通常是首选):
(fun x -> not << String.IsNullOrEmpty)
除此之外,这个 sn-p 正在创建一个 'a -> string -> bool 类型的函数,因为它忽略了参数 x。所以我想你可能真的想要:
(String.IsNullOrEmpty >> not)
【解决方案2】:
如果要使用参数x,可以使用管道运算符|>,而不是函数组合运算符(<< 或>>)。
fun x -> x |> String.IsNullOrEmpty |> not
但通常首选带有函数组合的无点样式。