【发布时间】:2021-07-14 17:28:10
【问题描述】:
我是 Haskell 和编程的初学者。我正在学习如何根据类型声明编写函数。如何编写函数,哪些类型在括号中声明,如 (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期望参数是一个函数。所以你对z的实现没有多大意义,因为你在这里接受两个 参数,并且由于第一个是一个函数,如果你用x + y实现它,它希望你可以将两个函数加在一起。 -
@WillemVanOnsem,感谢您的回复。因此,我是否需要分配函数以使函数返回整数,而不是分配 Integer ?
-
可能会有所帮助,签名函数
z :: (Integer -> Integer) -> Integer的另一个示例是z f = f 42。z是一个将另一个函数作为其参数的函数,该函数将应用于 42。所以z negate = -42、z (+1) = 43和z (*2) = 84
标签: haskell types type-systems