0

I know this question has been asked earlier, but the answer deviates from the main question.

Here is a method that checks if an element exists in Haskell

elem’ x (y : ys) = if x == y then True else elem’ x ys

What I'm confused about is that in Haskell (y : ys) this adds y to ys, so how does this function really checks if an element exists? Because I don't see any loop here except a recursive call passing the same y to ys.

Please enlighten me.

1
  • No, (y : ys) doesnt add y to ys. (y:ys) is the whole list. y is the fist element of that list. ys is the rest of the list. See stackoverflow.com/questions/1696751/… Commented Aug 3, 2017 at 11:37

2 Answers 2

6

I don't see any loop here except a recursive call passing the same y to ys

The recursive portion is passing the tail of the list to the elem' function, not the same list. Therefore, once it has gotten to the end of the list, the only tail remaining is the empty list, [], which should terminate in another function pattern like this:

elem' _ [] = False

Edit: Further clarification for your comment

You can picture the recursive calls like this:

-- assuming elem' is defined as:
elem' _ [] = False
elem' x (y : ys) = if x == y then True else elem' x ys

-- calling elem' trying to find 6 in [1..5]
elem' 6 (1 : [2, 3, 4, 5]) = if 6 == 1 then True else elem' 6 [2, 3, 4, 5]
elem' 6 (2 : [3, 4, 5])    = if 6 == 2 then True else elem' 6 [3, 4, 5]
elem' 6 (3 : [4, 5])       = if 6 == 3 then True else elem' 6 [4, 5]
elem' 6 (4 : [5])          = if 6 == 4 then True else elem' 6 [5]
elem' 6 (5 : [])           = if 6 == 5 then True else elem' 6 []
elem' 6 []                 = False
Sign up to request clarification or add additional context in comments.

3 Comments

Oh I see, thanks for clearing that confusion, but then how does the whole recursion work then? So lets say were looking for 4 in a [1..10], when we call the function, how does it check each element in the list?
I've added a visual example to the answer to try and help you picture what happens
Thank you Chad, Really appreciate your help, now it makes sense. So in every call, the head is changed which is why it loops right till the end.
0

What I'm confused about is that in Haskell (y : ys) this adds y to ys No it is not, that is a pattern matching feature, it is actually binding the first value of the list to y and the rest of it to ys. So, when you make the recursive call elem’ x ys you are evaluating the rest of the list. This is called tail recursion pattern

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.