Haskell函数类型变量

Uma*_*ooq 1 variables haskell types function

如果你有

foo :: a -> a -> Bool
Run Code Online (Sandbox Code Playgroud)

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

che*_*ner 5

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

foo :: a -> a -> Bool
foo _ _ = True
Run Code Online (Sandbox Code Playgroud)

用两个相同类型的参数调用它可以工作.

Prelude> foo 1 1
True
Prelude> foo 'x' 'x'
True
Run Code Online (Sandbox Code Playgroud)

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

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'
Run Code Online (Sandbox Code Playgroud)