Haskell函数类型变量(Haskell function type variables)

如果你有

foo :: a -> a -> Bool

这是否强制执行两种类型“a”是否相同?

If you have

foo :: a -> a -> Bool

Does this enforce both types "a" are the same?

最满意答案

是。 您可以使用一个忽略其参数的函数来观察它。

foo :: a -> a -> Bool foo _ _ = True

用相同类型的两个参数调用它。

Prelude> foo 1 1 True Prelude> foo 'x' 'x' True

使用不同类型的两个参数调用它会产生一个类型错误,确切的错误取决于您选择的类型。

Prelude> foo 1 'x' <interactive>:5:5: No instance for (Num Char) arising from the literal ‘1’ In the first argument of ‘foo’, namely ‘1’ In the expression: foo 1 'x' In an equation for ‘it’: it = foo 1 'x' Prelude> foo 'x' (1::Int) <interactive>:8:10: Couldn't match expected type ‘Char’ with actual type ‘Int’ In the second argument of ‘foo’, namely ‘(1 :: Int)’ In the expression: foo 'x' (1 :: Int) In an equation for ‘it’: it = foo 'x' (1 :: Int) Prelude> foo (1::Int) 'x' <interactive>:9:14: Couldn't match expected type ‘Int’ with actual type ‘Char’ In the second argument of ‘foo’, namely ‘'x'’ In the expression: foo (1 :: Int) 'x' In an equation for ‘it’: it = foo (1 :: Int) 'x'

Yes. You can observe this with a function that otherwise ignores its arguments.

foo :: a -> a -> Bool foo _ _ = True

Calling it with two arguments of the same type works.

Prelude> foo 1 1 True Prelude> foo 'x' 'x' True

Calling it with two arguments of different types produces a type error, the exact error depending on which types you choose.

Prelude> foo 1 'x' <interactive>:5:5: No instance for (Num Char) arising from the literal ‘1’ In the first argument of ‘foo’, namely ‘1’ In the expression: foo 1 'x' In an equation for ‘it’: it = foo 1 'x' Prelude> foo 'x' (1::Int) <interactive>:8:10: Couldn't match expected type ‘Char’ with actual type ‘Int’ In the second argument of ‘foo’, namely ‘(1 :: Int)’ In the expression: foo 'x' (1 :: Int) In an equation for ‘it’: it = foo 'x' (1 :: Int) Prelude> foo (1::Int) 'x' <interactive>:9:14: Couldn't match expected type ‘Int’ with actual type ‘Char’ In the second argument of ‘foo’, namely ‘'x'’ In the expression: foo (1 :: Int) 'x' In an equation for ‘it’: it = foo (1 :: Int) 'x'

更多推荐