简体   繁体   English

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

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

I am a beginner at Haskell and programming.我是 Haskell 和编程的初学者。 I am learning how to write functions based on type declarations.How to write function which types are declared in brackets like (a -> b) -> b.我正在学习如何根据类型声明编写函数。如何编写在括号中声明类型的函数,如 (a -> b) -> b。

When I tried this:当我尝试这个时:

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

I got an error like this:我收到这样的错误:

    • 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

If I give only one parameter assigned to the integer, it does type check,如果我只给一个分配给整数的参数,它会进行类型检查,

z f = 9

but no idea how to use that function as it show an error when i type z 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

How to write proper functions for such type declarations and how do they work?如何为此类类型声明编写适当的函数以及它们如何工作?

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

is the signature of a function that takes a a -> b and returns a c ;是接受a -> b并返回c的函数的签名; and a -> b is in turn a function that takes a a and returns a b .a -> b又是一个接受 a a并返回 a b的函数。

The definition定义

z x y = x + y

is incompatible with that type.与该类型不兼容。 This latter function, indeed, has signature后一个函数确实具有签名

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

which you can think of as the same as the following您可以将其视为与以下相同

z :: a -> b -> c

where the use of + in the definition has the effect of requiring that在定义中使用+的效果是要求

  • a be a Num , a是一个Num
  • and b and c be the same as a .bc是相同的a

When you write当你写

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

you are defining a function z which takes a function Integer -> Integer , doesn't use it at all, and returns 9 regardless.您正在定义一个函数z ,它接受一个函数Integer -> Integer ,根本不使用它,无论如何都返回9

So you could call z (+3) , ie passing the function "plus 3" to z , and you would get out 9 .所以你可以调用z (+3) ,即将函数“plus 3”传递给z ,你会得到9

In fact, you'll get 9 whenever you feed z with something that can be seen as Integer -> Integer .事实上,每当你给z提供一些可以被视为Integer -> Integer东西时,你就会得到9 This is obviously true for z (+3) , z (subtract 9) , and so on, but it's also true for z undefined , because undefined has type undefined :: a , ie it can take the place of any type, including Integer -> Integer .这对于z (+3)z (subtract 9)显然是正确的,但对于z undefined也是如此,因为undefined具有类型undefined :: a ,即它可以代替任何类型,包括Integer -> Integer

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM