Haskell - 投影函数的快速命名

问题描述 投票:-1回答:2

假设我想根据一些其他预定义函数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的currying(即.f只需要一个Int作为输入并返回一个(Int->Int)类型函数),我很惊讶我写不出来

f 2 = g

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

haskell currying function-composition first-class-functions
2个回答
4
投票

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

f 2 = g
f i j = i+j

相反,这可以像这样实现:

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

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
© www.soinside.com 2019 - 2024. All rights reserved.