F#是否提供功能参数 - 区别的是什么

时间:2017-10-01 11:02:07

标签: f#

我有几个函数可以对多项式进行基本算术运算。最初,我在没有明确提供参数的情况下定义了函数,但是当在其他函数中使用其中一些函数时,事情开始分崩离析,直到我将它们更改为接受参数。

代码更好地解释它:

//Multiplying a polynomial with a constant
let rec mulC = function
| (_,[])                    -> []
| (x,y::tail) when x > 0    -> x * y::mulC(x,tail)

//Adding two polynomials
let rec addE = function
| ([],[])                   -> []
| ([], y::ytail)            -> y::ytail
| (x::xtail,[])             -> x::xtail
| (x::xtail, y::ytail)      -> (x + y) :: addE(xtail,ytail)

//Multiplying a polynomial by x
let mulX = function
| []                    -> []
| xs                    -> 0::xs

//Multiplying two polynomials
let rec mul = function
| []                    -> []
| x::tail               -> addE (mulC x qs)
                                (mulX(mul qs tail))

现在,这给出了一个错误。这个值不是一个函数,不能在最后的函数mul中的addE中应用。

如果我将函数定义更改为此函数,则可以正常工作:

let rec mulC x ys =
match (x,ys) with
| (_,[])                    -> []
| (x,y::ys) when x > 0    -> x * y::mulC x ys

let rec addE xs ys =
match (xs, ys) with
| ([],[])                   -> []
| ([], y::ys)            -> y::ys
| (x::xs,[])             -> x::xs
| (x::xs, y::ys)      -> (x + y) :: addE xs ys

let mulX xs = 
match xs with
| []                    -> []
| xs                    -> 0::xs

let rec mul qs = function
| []                    -> []
| x::tail               -> addE (mulC x qs)
                                (mulX(mul qs tail))

是什么给出了?

1 个答案:

答案 0 :(得分:3)

function关键字会创建一个带一个参数的函数,并直接进入模式匹配。这三个函数都是等效的,其类型签名为(int * int) -> int。有一个2元组参数:

let add = function (a, b) -> a + b
let add' = fun x -> match x with (a, b) -> a + b
let add'' x = match x with (a, b) -> a + b

此函数的类型签名为int -> int -> int。有两个参数:

let add a b = a + b

但为什么会收到错误This value is not a function and cannot be applied.?因为addE接受一个参数并返回list。您应用了一个参数,因此类型系统推断您有一个列表,然后尝试将另一个参数应用于该列表,但list不是函数。只需使用以下代码就可以得到同样的错误:

[] 1