Home > Enterprise >  Haskell `elem` in nested list
Haskell `elem` in nested list

Time:12-18

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?

CodePudding user response:

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]])
  • Related