Reputation: 13
I have a list of strings like the following:
[ "aaa", "aaa", "aba", "aaa"]
I want to make a function that returns the first position of the list where there is an item containing the character 'b'. How can I do it in Haskell?
Upvotes: 0
Views: 7855
Reputation: 36375
You ask for the first position so I'm not clear whether you want an index value or the actual value. Here's a function that gives you a tuple containing both the index and the value at that index.
import Data.Maybe
firstOccurrenceOf :: Char -> [String] -> Maybe (Int, String)
firstOccurrenceOf c list =
listToMaybe $ filter (elem c . snd) $ zip [0..] list
listToMaybe
provides a safe alternative to head
which will return Nothing
instead of crashing on an empty list.
Upvotes: 1
Reputation: 1311
The List Utilities chapter of the Haskell Report describes a function findIndex
which finds the index of the first element of a list that satisfies an arbitrary predicate. It can be implemented as
findIndex p xs =
case [ i | (x, i) <- zip xs [0..], p x ] of
[] -> Nothing
e:_ -> Just e
With that, you can find the first element of the list that contains 'b'
with
findIndex ('b'`elem`) ["aaa", "aaa", "aba", "aaa"]
Upvotes: 2
Reputation: 12070
Here is a function that will do what you want:
getIndexWithb = findIndex ('b' `elem`)
You will need to import Data.List
to make this work. Also note that this function returns type Maybe Int
for the case that 'b'
never appears in any of the strings.
Usage:
> getIndexWithb [ "aaa", "aaa", "aba", "aaa"]
Just 2
Upvotes: 2