1
votes

I need a little hint for my Haskell-exercise.

First I had to implement a program, which checks if an integer is even or not... my code so far, this works perfect

isEven :: Int -> Bool
isEven 0 = True
isEven (-1) = False
isEven 1 = False
isEven x
        |x<0 = isEven (x+2)
        |x>0 = isEven (x-2)

Next i have to use this function to count all even Integers in a List. The code i have so far:

countEven :: [Int] -> Int
countEven (x:xs) = (isEven x)
                           |True = 1 + countEven xs
                           |False = 0 + countEven xs

I want to use the isEven-returncode (True|False) to determine wether to count my Int up or not. I dont know how to continue scripting this one.

In this case it says

parse error on input '|'

I tried another script and there it gives the error

Couldn't match expected type 'Int' with actual type 'Bool'.

Thus the function isEven is working, but I don't know exactly how to convert the "True"-statement into my if statement.

1
You don't need isEven (-1) = False if you chance the negative case to | x<0 = isEven (-x).Landei

1 Answers

4
votes

Any of the following work:

countEven (x:xs) = if isEven x then 1 + countEven xs else 0 + countEven xs
countEven (x:xs) = (if isEven x then 1 else 0) + countEven xs
countEven (x:xs) = case isEven x of
    True -> 1 + countEven xs
    False -> 0 + countEven xs
countEven (x:xs)
   | isEven x  = 1 + countEven xs
   | otherwise = 0 + countEven xs