超级基本问题 - 但我似乎无法得到一个明确的答案.以下函数将无法编译:
randomfunc :: a -> a -> b
randomfunc e1 e2
| e1 > 2 && e2 > 2 = "Both greater"
| otherwise = "Not both greater"
main = do
let x = randomfunc 2 1
putStrLn $ show x
Run Code Online (Sandbox Code Playgroud)
我很困惑为什么这不起作用.两个参数都是'a'(Ints)类型,返回参数是'b'(String)类型?
错误:
"Couldn't match expected type ‘b’ with actual type ‘[Char]’"
Run Code Online (Sandbox Code Playgroud)
不完全的.你的函数签名表示:对于所有类型的a和b,randomfunc将返回一个类型的东西b,如果给定类型的两件事情a.
但是, randomFunc返回a String([Char]).而且,由于你比较e1与2对方,你不能使用所有 a的,只有那些可以搭配>:
(>) :: Ord a => a -> a -> Bool
Run Code Online (Sandbox Code Playgroud)
请注意,e1 > 2还需要一种方式来创建这样的一个a来自2:
(> 2) :: (Num a, Ord a) => a -> Bool
Run Code Online (Sandbox Code Playgroud)
因此要么使用特定类型,要么确保正确处理所有这些约束:
randomfunc :: Int -> Int -> String
randomFunc :: (Ord a, Num a) => a -> a -> String
Run Code Online (Sandbox Code Playgroud)