我们如何将不带参数的函数转换为单参数函数?

Tim*_*Tim 0 f# design-patterns functional-programming

https://www.slideshare.net/ScottWlaschin/fp-patterns-ndc-london2014

坏消息:组合模式仅适用于具有一个参数的函数!

好消息!每个功能都是一个参数功能!

通过部分应用,我们可以将具有两个参数的函数转换为具有一个参数的函数。例如

let add x y = x + y 
let add x = (fun y -> x + y)

let add1 = (+) 1  
let three = add1 2 
Run Code Online (Sandbox Code Playgroud)

我们如何将不带参数的函数转换为单参数函数?

gle*_*nsl 7

There are no functions without parameters, and there's no conversion going on with multi-parameter functions. As the quote says, "every function is a one parameter function". There's always just one parameter, no more and no less.

What you might consider a no-parameter function is probably a function that takes a single parameter of type unit:

let f () = ...
Run Code Online (Sandbox Code Playgroud)

The unit type has only one value, () (which is also called "unit"), hence it carries no information, but it's still technically a value. You might think of it as the empty tuple.

A two-parameter function is actually a function that takes one parameter and returns another function that takes another parameter. Functions are first-class, remember, meaning they are values that can be returned from functions and bound to variable names. These two forms are therefore equivalent, the former is just syntax sugar for the latter:

let f a b = ...
let f = fun a -> fun b -> ...
Run Code Online (Sandbox Code Playgroud)

A three-parameter function is a function that returns a function that returns a function, and so on. This is called currying. And, with curried functions, partial function application is just ordinary function application. The function application just happens to return a function rather than some other value.

  • 为了进一步说明,形式为“ let f(a,b)= a + b”的函数不是具有两个参数的函数,而是具有一个参数类型为“ int * int”或“ int 2-”的函数。元组”。 (3认同)