Reputation: 404
I would like to search a list of a list of Chars, [[Char]]
determine whether a Char is within the list, returning true or false. So far I have this,
scanBoard :: [[Char]] -> Bool
scanBoard board
| 'r' `elem` board = True
| 'i' `elem` board = True
| otherwise = False
Thanks!
Upvotes: 0
Views: 355
Reputation: 11366
we can create a predicate to test on a character:
\c -> (c == 'r') || (c == 'i')
then we can check that any sublist has any such char
scanBoard :: [[Char]] -> Bool
scanBoard = any $ any pred where
pred = \c -> (c == 'r') || (c == 'i')
Upvotes: 6
Reputation: 21757
For the purpose of searching, you can convert your list of lists to a single list using concat
, and then search within the derived list using elem
, like so:
scanBoard :: [[Char]] -> Bool
scanBoard board
| elem 'r' $ concat board = True
| elem 'i' $ concat board = True
| otherwise = False
Alternatively, we can do this recursively as shown below:
scanBoard :: [[Char]] -> Bool
scanBoard [[]] = False
scanBoard [x] = (elem 'r' x || elem 'i' x)
scanBoard board@(x:xs) = (elem 'r' x || elem 'i' x) || scanBoard xs
This will eliminate the need for the concat
operation, and allow use to work directly with the list of lists using pattern matching.
Upvotes: 2