So I'm following the tutorial Learn you a Haskell for Great Good! and so far I absolutely love Haskell. But in one of the functions mentioned in the tutorial I'm getting a warning that the if-statement is redundant.
Edit: Let me be clear, the intent of the function is to act exactly the same way the elem function works (the one that is provided with Haskell by default).
Here's the original function:
elem' :: (Eq a) => a -> [a] -> Bool
elem' y ys = foldl (\acc x -> if x == y then True else acc) False ys
Originally there were two warnings, one was eta reduction, so I removed the ys from the beginning and end of the function name to arrive at:
elem' :: (Eq a) => a -> [a] -> Bool
elem' y = foldl (\acc x -> if x == y then True else acc) False
Now I tried to reduce the function to the following and it results in an error:
elem' :: (Eq a) => a -> [a] -> Bool
elem' y = foldl (\acc x -> x == y)
I think I'm just very new to Haskell and can't see the obvious solution. Can someone tell me what code change would keep the function working correctly and yet remove the compiler warning?
if x == y then True else acc
is the same as x == y || acc
.
Typing your last definition into GHCi
without a type annotation:
Prelude> let elem' y = foldl (\acc x -> x == y)
Prelude> :t elem'
elem' :: (Eq b) => b -> Bool -> [b] -> Bool
It doesn't match your declared type.
You forgot the False
at the end! If you add it in:
Prelude> let elem' y = foldl (\acc x -> x == y) False -- note the False at the end
Prelude> :t elem'
elem' :: (Eq b) => b -> [b] -> Bool
It has the right type!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With