简体   繁体   中英

How to check if an element exists in list in haskell?

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM