为什么Haskell不允许我对其函数定义更加宽松?

dev*_*ium 0 haskell functional-programming

我发现这一点有点惊讶

head' :: [a] -> b
head' (x:xs) = x
Run Code Online (Sandbox Code Playgroud)

提出一个

Couldn't match expected type `b' with actual type `a'
  `b' is a rigid type variable bound by
      the type signature for head' :: [a] -> b at type_test.hs:1:10
  `a' is a rigid type variable bound by
      the type signature for head' :: [a] -> b at type_test.hs:1:10
In the expression: x
In an equation for head': head' (x : xs) = x
Run Code Online (Sandbox Code Playgroud)

这是为什么?我假设Haskell会允许我像我想要的那样松懈,并且会发现没问题[a] -> b.

谢谢

Ben*_*aft 10

功能类型签名不正确.由于输入是类型[a],输出将始终是类型a.类型签名[a] -> b表示该函数将接受任何事物列表,并返回任何(可能是不同的)类型的东西,这是不正确的 - 它只能返回相同类型的东西a.

  • 这是不正确的,因为那种类型,`[a] - > b`与类似`[Int] - > String`的类型兼容,而`head`显然不是. (2认同)
  • @devoured这些短语正是类型系统试图说的那种东西.它希望尽可能一般,但不是更一般.特别是,您似乎熟悉具有子类型的类型系统,因此您可以忘记Int到Any.Haskell确实有子类型,但它更加微妙,旨在使类型尽可能具体. (2认同)