Home > Software engineering >  How could i manipulate a list comprehension?
How could i manipulate a list comprehension?

Time:05-26

First time posting, sorry if I am doing something wrong or am unclear about my question

I'm pretty new to Haskell and I am having a hard time figuring out how could I manipulate a list comprehension to show me what I want. I have two functions that give me lists of tuples(they are basically matrices, one of which is full, the other is random)

I want to create a new list (matrix) with the list comprehension which would return whether list2 tuple was the same as list1 tuple.

For example:

list1 = [(0,0),(0,1),(0,2),(1,0),(1,1),(1,2),(2,0),(2,1),(2,2)]
list2 = [(1,0),(1,1)]
result = [False, False, False, True, True, False, False, False, False]

But the list comprehension I've written gives me a cartesian product

[False,False,False,True,False,False,False,False,False,False,False,False,False,True,False,False,False,False]

The list comprehension continues to compare the tuple from List2 even after it has found the same one in List1.

This is how I've written my list comprehension :

[ (x==y) | x <- (list2), y <- (list1)]

I'm pretty sure there must be some sort of predicate that can be written in the list comprehension to get what I want, but I've no clue how to realise that.

CodePudding user response:

This is e membership check, so you can implement this as:

[ x `elem` list2 | x <- list1 ]

But simpler is probably to work with map :: (a -> b) -> [a] -> [b]:

map (`elem` list2) list1
  • Related