或者,换句话说,是否需要添加如下所述的约束?
工作代码,函数f的最小类型声明:
data ZeroPositive = Zero | Positive Int deriving Show
f :: [Int] -> [ZeroPositive]
f [] = []
f (0:xs) = Zero:(f xs)
f (x:xs) = (Positive x):(f xs)
main = putStrLn . show $ f [0,2]
Run Code Online (Sandbox Code Playgroud)
结果:
[Zero,Positive 2]
Run Code Online (Sandbox Code Playgroud)
破坏的代码与无用的约束ZeroPositive:
data ZeroPositive = Zero | Positive Int deriving Show
f :: ZeroPositive => [Int] -> [ZeroPositive]
f [] = []
f (0:xs) = Zero:(f xs)
f (x:xs) = (Positive x):(f xs)
main = putStrLn . show $ f [0,2]
Run Code Online (Sandbox Code Playgroud)
结果:
99.hs:3:7:
Couldn't match expected type `ZeroPositive' with actual type `[t0]'
In the pattern: []
In an equation for `f': f [] = []
99.hs:3:12:
Couldn't match expected type `[Int] -> [ZeroPositive]'
with actual type `[a0]'
In the expression: []
In an equation for `f': f [] = []
...
99.hs:6:32:
Couldn't match expected type `ZeroPositive' with actual type `[t0]'
In the first argument of `f', namely `[0, 2]'
In the second argument of `($)', namely `f [0, 2]'
In the expression: putStrLn . show $ f [0, 2]
Run Code Online (Sandbox Code Playgroud)