Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

throws a error, that types can not be matched.

Do I miss something here?

like image 768
code_noob Avatar asked Dec 18 '21 10:12

code_noob


1 Answers

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.

Another option, as @amalloy described is to concatenate all the sublists into a list, and then perform an elem check on these, so:

elem X (concat [[X, X, X], [O, O, O]])
like image 122
Willem Van Onsem Avatar answered Nov 24 '22 04:11

Willem Van Onsem