MrD
MrD

Reputation: 5086

Haskell MaybeInt Query on elemIndex

I have the following function

eC :: Char -> [Char] -> Char
eC x z = z !! elemIndex x cA

Where cA is a list of chars.

However, I get returned

Type error in application
*** Expression     : z !! elemIndex x cA
*** Term           : elemIndex x cA
*** Type           : Maybe Int
*** Does not match : Int

I don't really understand what this means... Can somebody please help?

Upvotes: 0

Views: 912

Answers (3)

Sassa NF
Sassa NF

Reputation: 5406

This means that elemIndex returns Maybe Int, but you cannot use Maybe Int as the index in !!.

I am sure this can be solved simpler. I suggest looking into zip and find.

Edit: oooh, zip and lookup is even more straightforward in this case.

Upvotes: 1

viorior
viorior

Reputation: 1803

You could also use just Functor

eC :: Char -> [Char] -> Maybe Char
eC x z = (z !!) `fmap` (elemIndex x cA)

Upvotes: 0

J. Abrahamson
J. Abrahamson

Reputation: 74344

elemIndex might fail, after all, the element may not be in the list. This failure mode should be in your final type (unless you handle it somehow).

eC :: Char -> [Char] -> Maybe Char

Then you can propagate the failure

eC x z = case elemIndex x cA of
  Nothing -> Nothing
  Just ix -> Just (z !! ix)

Though it's worth noting that (!!) will throw uncatchable exceptions if you have an out-of-bounds error. You may want to catch that as well by combining errors

eC x z = case elemIndex x cA of
  Nothing -> Nothing
  Just ix -> index z ix   -- index returns values wrapped in Maybe

You can do this more simply by using the Monad instance of Maybe.

eC x z = do ix <- elemIndex x cA
            index z ix

Or even

eC x z = elemIndex x cA >>= index z

Upvotes: 1

Related Questions