Haskell 不使用 odd 函数检查数字是否为奇数的函数
Haskell function checking if number is odd, without using the odd function
有人可以帮我吗?我正在尝试编写一个函数来检查 x 是否为奇数,而不使用 odd 函数。
像这样它不起作用,但我不知道为什么。
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 .. ]
问题出在行
x elem oddList
哪个应该说
elem x oddList
因为 elem
是一个函数 elem :: Eq a => a -> [a] -> Bool
,或者
x `elem` oddList
您在何处使用反引号表示中缀函数应用程序。
请注意,您的函数没有按预期运行。对于奇数它最终会 return True
(虽然对于大参数需要很长时间)但是对于偶数它永远不会 return,因为函数不能证明偶数是从未在列表中 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..]
或
f = (`elem` [1,3..])
有人可以帮我吗?我正在尝试编写一个函数来检查 x 是否为奇数,而不使用 odd 函数。 像这样它不起作用,但我不知道为什么。
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 .. ]
问题出在行
x elem oddList
哪个应该说
elem x oddList
因为 elem
是一个函数 elem :: Eq a => a -> [a] -> Bool
,或者
x `elem` oddList
您在何处使用反引号表示中缀函数应用程序。
请注意,您的函数没有按预期运行。对于奇数它最终会 return True
(虽然对于大参数需要很长时间)但是对于偶数它永远不会 return,因为函数不能证明偶数是从未在列表中 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..]
或
f = (`elem` [1,3..])