3

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). Commented Jan 23, 2016 at 12:31

1 Answer 1

5

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
Sign up to request clarification or add additional context in comments.

3 Comments

compiled without any errors, still gives me following error when trying countEven [2,4,5,6]: Non-exhaustive pattern ins function countEven what does that mean?
okay, found the mistake by myself :) adding countEven [] = 0 made the thing
@Side2005 If this answer works for you, can you accept it please? (click the tick below the vote arrows)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.