Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redundant if statement warning in haskell

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?

like image 345
Asaf Avatar asked Nov 08 '11 14:11

Asaf


2 Answers

if x == y then True else acc is the same as x == y || acc.

like image 197
augustss Avatar answered Sep 19 '22 01:09

augustss


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!

like image 29
Matt Fenwick Avatar answered Sep 20 '22 01:09

Matt Fenwick