I'm trying to write a function in Haskell that takes 4 integers as input and counts how many of that input numbers are equal to the first integer.
For example:
howManyEq 3 4 5 6 returns 0
howManyEq 3 4 3 5 returns 2
howManyEq 3 4 3 3 returns 3
howManyEq 3 3 3 3 returns 4
This is the function I have created so far, it works for the first instance when there is no input matching the first integer. But it doesn't count the first 3 when there are other matching integers, it always has one less counted.
howManyEq :: Int -> Int-> Int -> Int -> Int
howManyEq a b c d = count (head (toList a b c d)) (tail (toList a b c d))
count :: Int -> [Int] -> Int
count x [] = 0
count x (y:ys)
| x == y = 1 + (count x ys)
| otherwise = count x ys
toList :: Int -> Int-> Int -> Int -> [Int]
toList a b c d = [a,b,c,d]
My function gives me:
howManyEq 3 4 5 6 returns 0
howManyEq 3 4 3 5 returns 1
howManyEq 3 4 3 3 returns 2
howManyEq 3 3 3 3 returns 3
I'm not sure how to count the first integer when the other input integers are equal.
howManyEq
can never return 1. Create function that returns+ 1
to what you're returning now. Feed that result into a function that is defined asf 1 = 0
andf a = a
... – Dair1
. If that's the case, this is a typical off by one error. – Willem Van OnsemhowManyEq 3 4 3 5
should return 2 because it counts both instances of 3. ButhowManyEq 3 4 5 6
should return 0. I know its kinda illogical, but this is the way my teacher wants it for some reason. – T-Bird