Haskell参数不对?

时间:2014-03-24 23:44:31

标签: haskell

我是新的haskell leaner,我的代码如下:

{-- snippet all --}
{- | Our usual CustomColor type to play with -}
data CustomColor =
  CustomColor {red :: Int,
               green :: Int,
               blue :: Int}
  deriving (Eq, Show, Read)

{- | A new type that stores a name and a function.

The function takes an Int, applies some computation to it, and returns
an Int along with a CustomColor -}
data FuncRec =
    FuncRec {name :: String,
             colorCalc :: Int -> (CustomColor, Int)}

plus5func color x = (color, x + 5)

purple = CustomColor 255 0 255

plus5 = FuncRec {name = "plus5", colorCalc = plus5func purple }
always0 = FuncRec {name = "always0", colorCalc = \_ -> (purple, 0)}
{-- /snippet all --}

在“colorCalc = plus5func purple”行中,为什么在plus5func之后只有一个参数(“purple”),实际上plus5func应该需要两个参数?

3 个答案:

答案 0 :(得分:4)

定义

plus5func color x = (color, x + 5)

相当于

plus5func color = f
    where f x = (color, x + 5)

换句话说:plus5func实际上只接受一个参数(color)广告返回一个函数f。这个返回的函数接受一个参数(x)并返回最终的颜色& int对。

这是"二进制"函数通常用Haskell和其他函数语言表示。这种风格被命名为#34; Currying"在数学家/计算机科学家" Haskell Curry"。

之后

你可以使用这样的函数,因为它们是二进制函数,因为

plus5func color x
= (plus5func color) x
= f x                      {- where f is as above -}
= (color, x + 5)

作为奖励,您可以获得部分应用程序",即传递更少的参数(在本例中为一个)并获取要传递的重新参数的函数的能力(在这种情况下f。)

所以,行

plus5 = FuncRec {name = "plus5", colorCalc = plus5func purple }

实际上意味着

plus5 = FuncRec {name = "plus5", colorCalc = f }
     where f x = plus5func purple x

答案 1 :(得分:3)

haskell中的所有函数都隐含curried。这意味着当你编写像

这样的函数时
f x y = x + y

你真的在做更像

的事情
f = \x -> \y -> x + y

也就是说,f是一个将x映射到另一个将y映射到x + y的函数的函数。

所以f 5实际上是函数\y -> 5 + y

答案 2 :(得分:0)

您可以部分地将参数应用于某个功能。这意味着您现在提供第一个参数,稍后提供第二个参数。

例如:

(+) :: Num a => a -> a -> a
(1+) :: Num a => a -> a
(1+1) :: Num a => a