括号中的类型声明如何在 Haskell 中工作,例如 (Integer -> Integer) -> Integer

How type declarations in brackets work in Haskell like (Integer -> Integer) -> Integer

我是 Haskell 和编程的初学者。我正在学习如何编写基于类型 declarations.How 的函数来编写在括号中声明的类型的函数,例如 (a -> b) -> b.

当我尝试这个时:

z :: (Integer -> Integer) -> Integer
z x y = x + y

我遇到这样的错误:

    • Couldn't match expected type ‘Integer’
                  with actual type ‘(Integer -> Integer) -> Integer -> Integer’
    • The equation(s) for ‘z’ have two arguments,
      but its type ‘(Integer -> Integer) -> Integer’ has only one

如果我只给整数分配一个参数,它会进行类型检查,

z f = 9

但不知道如何使用该函数,因为它在我键入 z 9 时显示错误:

  • No instance for (Num (Integer -> Integer))
        arising from the literal ‘5’
        (maybe you haven't applied a function to enough arguments?)
    • In the first argument of ‘z’, namely ‘5’
      In the expression: z 5
      In an equation for ‘it’: it = z 5

如何为此类类型声明编写适当的函数以及它们如何工作?

z :: (a -> b) -> c

是一个函数的签名,它接受一个a -> b和returns一个c;而 a -> b 又是一个接受 a 和 returns 一个 b.

的函数

定义

z x y = x + y

与该类型不兼容。后一个函数确实具有签名

z :: Num a => a -> a -> a

你可以认为和下面的一样

z :: a -> b -> c

在定义中使用 + 的效果是要求

  • aNum,
  • bca相同。

当你写作时

z :: (Integer -> Integer) -> Integer
z f = 9

您正在定义一个函数 z,它接受一个函数 Integer -> Integer,根本不使用它,并且 returns 9 无论如何。

所以你可以调用 z (+3),即将函数“plus 3”传递给 z,你会得到 9.

事实上,只要您向 z 喂食可以看作 Integer -> Integer 的东西,您就会得到 9。对于 z (+3)z (subtract 9) 等显然是这样,但对于 z undefined 也是如此,因为 undefined 具有类型 undefined :: a,即它可以采用任何类型的位置,包括 Integer -> Integer.