Peine
Peine

Reputation: 101

How to use where statement?

I am new to Haskell. I have a piece of code that checks whether an integer number is contained in a list.

myElem' :: Int -> [Int] -> Bool
myElem' a xs = foldl f' False xs
  where f' b x = if x==a then True else b

I don't understand how the code works from ‘Where’. I know that the f' is an expression and the whole sentance is used to define the f'. b should be a Boolean but why? Is the x equal to xs? Many thanks!

Upvotes: 0

Views: 134

Answers (1)

Zeta
Zeta

Reputation: 105955

Lets go through it step by step. The type of foldl is

foldl :: (a -> b -> a) -> a -> [b] -> a

Your where statement defines the function f', which takes two values and returns a third one. So all we know at that time is that f has the following type:

f' :: a -> b -> c

Since if ... then A else B needs both branches to have the same type, this concludes that your function will return a Bool (your first branch returns True). Therefore

f' :: a -> b -> Bool

But the second branch returns the first argument. So the first argument must be a Bool too (otherwise you couldn't use it for foldl, see above).

f' :: Bool -> b -> Bool

Since x == a, this indicates that x should be of the same type as a. If we know have a look at myElem', we see that a is of type Int, and therefore your auxiliary function f' has type

f' :: Bool -> Int -> Bool

The x in the definition of f' is not equal to xs. Instead it is just another variable. foldl will walk through xs and use f' on all elements in order to reduce the list to one single value.

Upvotes: 3

Related Questions