Reputation: 23
I have a little problem with my homework to school. I have to write code, which will find any x (int or letter) in a list of lists.
I have something like this:
find x xxs = [ [ x | x <- xs, x `elem` xs ] | xs <- xxs ]
Hugs98 accept it without any exception, but it doesn't work.
Input: find 2 [[1,1,1,1],[4,4,4,4],[3,3,3]]
Output: [[1,1,1,1],[4,4,4,4],[3,3,3,3]]
Upvotes: 2
Views: 175
Reputation: 62848
With a little renaming, I think you just wrote this:
find x yss = [ [ y | y <- ys, y `elem` ys ] | ys <- yss ]
I don't think that's what you meant to do. (In your code, you've got two variables named x
, one shadowing the other.)
Your question doesn't state what tools you are or aren't allowed to use.
Clearly elem
finds stuff in a list. And by "finds", I mean it returns a Bool
indicating whether the target item is present or not. But how to handle a list of lists?
A list comprehension always returns a list, so if you were hoping for find
to return a Bool
, you don't want a list comprehension.
You can use map
to apply elem
to every list in the list of lists - but now you have a list of Bool
s. There are two ways to deal with that. One slightly kludgy way is to use elem
to see if the list contains True
anywhere. But a more sane way is to use the built-in or
function, which takes the logical-OR of a list of Bool
s. (There is also a corresponding and
function.)
find x yss = or (map (x `elem`) yss)
There's another way you can do this too; there's a built-in function called any
, which applies a function to a list of stuff and returns True
if the supplied function ever returns True
. So you can do
find x yss = any (x `elem`) yss
Upvotes: 5