Search code examples
haskellfindlist-comprehension

Find and return first string which contains char (Haskell)


I am trying to write a function which loops through a list of strings that looks like this:

["     |     ","     #     ","     *     ","     |     ","     #     "]

I am trying to find and return the first element that contains either '|', '#', or '*', depending on the users choice.

I came up with this solution:

test :: Char -> [String] -> Maybe Char
test c (x:xs) = find (== c) $ concatMap (filter (/=' ')) (reverse xs)

And I get this output:

ghci> test '*' ["     |     ","     #     ","     *     ","     |     ","     #     "]
Just '*'

Which finds the element, but I want it to return the element without altering it (removing the spaces). How can I do this without filtering out the spaces?

This is the output I want:

ghci> test '*' ["     |     ","     #     ","     *     ","     |     ","     #     "]
"     *     "

Solution

  • Since you've tagged your question with ,

    test :: Eq a => a -> [[a]] -> Maybe [a]
    test c xs = listToMaybe [s | s <- xs, elem c s]
    

    should do the job.

    > test '*' ["     |     ","     #     ","     *     ","     |     ","     #     "]
    Just "     *     "
    
    > test '-' ["     |     ","     #     ","     *     ","     |     ","     #     "]
    Nothing
    
    > :i listToMaybe
    listToMaybe :: [a] -> Maybe a   -- Defined in `Data.Maybe'