Can anyone help me with that? I am trying to write a function checking if an x is odd, without using the odd function. Like this it does not work but i don't know why.
ugerade :: Integral a => a -> Bool
ugerade x
|x elem oddList = True
|otherwise = False
where
oddList=[x | x<-[1,3..]]
Error
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 .. ]
The problem is in the line
x elem oddList
which should either say
elem x oddList
since elem
is a function elem :: Eq a => a -> [a] -> Bool
, or
x `elem` oddList
where you are using backticks to indicate infix function application.
Note that your function does not work as you intended. For odd numbers it will eventually return True
(although it takes a long time for large arguments) but for even numbers it will never return, because the function cannot prove that an even number is never in the list oddList
.
Also note that writing
oddList = [ x | x <- [1,3..] ]
is redundant, you could just write
oddList = [1,3..]
instead, and also writing
f x | x `elem` oddList = True
| otherwise = False
is redundant, where you could just write
f x = x `elem` oddList
or even
f x = x `elem` [1,3..]
or
f = (`elem` [1,3..])