F# 不包含 Haskell 中可用的一些基本函数(主要是因为 F# 程序员通常更喜欢显式的编程风格,并且仅在不损害可读性的最明显的情况下使用无点风格)。
但是,您可以像这样定义一些基本组合器:
// turns curried function into non-curried function and back
let curry f (a, b) = f a b
let uncurry f a b = f (a, b)
// applies the function to the first/second element of a tuple
let first f (a, b) = (f a, b)
let second f (a, b) = (a, f b)
现在您可以使用组合器实现添加两个字符串长度的函数,如下所示:
let addLengths =
uncurry (( (first String.length) >> (second String.length) ) >> (curry (+)))
这构造了两个适用String.length
于元组的第一个/第二个元素的函数,然后组合它们,然后使用添加元组的元素+
。整个东西都被包裹起来了uncurry
,所以你得到了一个 type 的函数string -> string -> int
。