Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Haskell `elem` in nested list

I want to check for an element in a nested list.

I already tried several ways but I will always get the wrong result or some errors.

[X] `elem` [[X,X,X],[O,O,O]]

returns False but should be True

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

X `elem` [[X,X,X],[O,O,O]]

throws a error, that types can not be matched.

Do I miss something here?

>Solution :

The elements of the list are sublists, and there is no [X] sublist in the list.

You can check if any of the elements of the sublists contain X with:

any (elem X) [[X, X, X], [O, O, O]]

or with elem as infix operator:

any (X `elem`) [[X, X, X], [O, O, O]]

but these are semantically completely identical.

These will check if for any of the sublists (here [X, X, X] and [O, O, O]), X is an element of these lists.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading