Haskell-投影功能的快速命名

时间:2019-04-05 06:30:08

标签: haskell currying function-composition first-class-functions

假设我想根据其他一些预定义函数f定义函数g,如下所示:

f :: Int -> Int -> Int
f 2 b = g b
f _ _ = 1

也就是说,我要定义投影f(2,_) : Int->Intg(_) : Int->Int相同。很高兴,Haskell具有一流的功能,因此像以下squarePlusOne这样的定义是有效和标准的:

plusOne :: Int -> Int
plusOne i = i+1
square :: Int -> Int
square i = i*i
squarePlusOne :: Int -> Int
squarePlusOne = plusOne . Square

随着Haskell的流动(即f仅接受一个Int作为输入并返回一个(Int->Int)类型的函数),我很惊讶我无法编写

f 2 = g

为什么不呢?还是还有其他语法?

2 个答案:

答案 0 :(得分:4)

实际上,编写f 2 = g是定义f的有效方法。但是,以这种方式定义函数时,请记住,必须使用相同的模式签名来定义整个函数。也就是说,您可能不会通过编写来耗尽您的功能

f 2 = g
f i j = i+j

相反,可以这样实现:

f 2 = g
f i = (\j-> i+j)

答案 1 :(得分:2)

您可以使用const函数,该函数创建一个忽略其参数的函数以返回固定值。

f :: Int -> Int -> Int
f 2 = g            -- f 2 x = g x
f _ = const 1      -- f _ x = const 1 x == (\_ -> 1) x == 1