任何人都可以帮助我吗?我正在尝试编写一个函数来检查x是否为奇数,而不使用奇函数。 像这样它不起作用,但我不知道为什么。
ugerade :: Integral a => a -> Bool
ugerade x
|x elem oddList = True
|otherwise = False
where
oddList=[x | x<-[1,3..]]
错误
Could not deduce (Num t0) arising from the literal ‘1’
from the context (Integral a)
bound by the type signature for ugerade :: Integral a => a -> Bool
at /Users/Mauritius/Desktop/Haskell/u02/2-2/funktionen.hs:24:11-33
The type variable ‘t0’ is ambiguous
Relevant bindings include
oddList :: [t0]
(bound at /Users/Mauritius/Desktop/Haskell/u02/2-2/funktionen.hs:29:4)
Note: there are several potential instances:
instance Integral a => Num (GHC.Real.Ratio a)
-- Defined in ‘GHC.Real’
instance Num Integer -- Defined in ‘GHC.Num’
instance Num Double -- Defined in ‘GHC.Float’
...plus three others
In the expression: 1
In the expression: [1, 3 .. ]
In a stmt of a list comprehension: x <- [1, 3 .. ]
答案 0 :(得分:4)
问题出在
行x elem oddList
应该说
elem x oddList
因为elem
是函数elem :: Eq a => a -> [a] -> Bool
或
x `elem` oddList
您正在使用反引号来指示中缀函数应用程序。
请注意,您的功能无法按预期工作。对于奇数,它最终将返回True
(尽管大型参数需要很长时间)但是对于偶数,它将永远不会返回,因为该函数无法证明偶数在永远不在列表中{{1} }。
另请注意写作
oddList
是多余的,你可以写
oddList = [ x | x <- [1,3..] ]
相反,也写作
oddList = [1,3..]
是多余的,你可以写
f x | x `elem` oddList = True
| otherwise = False
甚至
f x = x `elem` oddList
或
f x = x `elem` [1,3..]