Find a set item in a list with anonymous values

I want to find in this list:

test = [ (1,1,1,0) , (1,1,1,1) , (1,3,1,0) , (1,4,2,0) , (1,5,2,0) , (1,6,2,0) ,
         (3,1,3,5) , (3,2,3,4) , (3,3,3,3) , (3,4,4,1) , (3,5,4,2) , (3,6,4,6) ,
         (2,1,1,2) , (2,2,1,5) , (2,3,1,0) , (2,4,2,4) , (2,5,2,1) , (2,6,2,0) ,
         (4,1,3,0) , (4,2,3,0) , (4,3,3,0) , (4,4,4,0) , (4,5,4,0) , (4,6,4,0) ,
         (5,1,5,1) , (5,2,5,6) , (5,3,5,0) , (5,4,6,2) , (5,5,6,3) , (5,6,6,0) ,
         (6,1,5,3) , (6,2,5,2) , (6,3,5,4) , (6,4,6,5) , (6,5,6,6) , (6,6,6,1) ]

A tuple with anonymous elements, for example (1,1, X, X), where X can be any value:

*> find (==(1,1,1,0)) test
Just (1,1,1,0)

I want to be able to do:

*> find (==(1,1,X,X)) test
(1,1,1,0)
(1,1,1,1)

Actual question: is there any anonymous variable (for example, "_" in the prolog) to match any value?

+3
source share
2 answers

Use filterand pattern matching.

Prelude> :t filter
filter :: (a -> Bool) -> [a] -> [a]

Performs a function that matches things:

filter (\x -> case x of (1,1,_,_) -> True; _ -> False) ...
+5
source

You can use list comprehension.

[x | x@(1,1,_,_) <- test]

This works because when you have a pattern that may fail on the left side <-, values ​​that do not match the pattern are filtered out.

+5
source

All Articles