使用F#的默认编程风格

Bub*_*a88 6 f# tacit-programming

这不是一个实际重要的问题,但我想在F#中看到默认编程的一个例子,其中我的无函数可以有多个参数(不是列表或元组的形式).

其次,这些函数如何操作复杂的数据结构.我在F#Interactive中试用它,但还没有成功.

我试过,例如:

> (fun _ -> (fun _ -> (+))) 333 222 111 555
Run Code Online (Sandbox Code Playgroud)

这是对的吗?

和:

> (fun _ -> (fun _ -> (+))) "a" "b" "c" "d";;  

val it : string = "cd"
Run Code Online (Sandbox Code Playgroud)

Tom*_*cek 4

F# 不包含 Haskell 中可用的一些基本函数(主要是因为 F# 程序员通常更喜欢显式编程风格,并且仅在最明显的情况下使用 pointfree 风格,这样不会损害可读性)。

但是,您可以像这样定义一些基本组合器:

// 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)
Run Code Online (Sandbox Code Playgroud)

现在您可以实现使用组合器将两个字符串的长度相加的功能,如下所示:

let addLengths = 
  uncurry (( (first String.length) >> (second String.length) ) >> (curry (+)))
Run Code Online (Sandbox Code Playgroud)

这构造了两个应用于元组的第一个/第二个元素的函数String.length,然后组合它们,然后使用添加元组的元素+。整个事情都被包裹起来uncurry,所以你得到了一个 type 的函数string -> string -> int