Kelsey Abreu
Kelsey Abreu

Reputation: 1124

How would I turn this into a tail recursion? Haskell

I'm trying to get the the index of an element that is in a list.

However the problem I am having is when the element isn't in the list.

I'm thinking that maybe tail recursion is in order, but I'm not really sure how to go about it.

whatIndex sought [] = -1
whatIndex sought (a:xs) = 
    if sought == a
        then 0
        else 1 + whatIndex sought xs

Edit:

When it's not in the list, it should return -1

Example:

whatIndex 3 [1,2,3] == 2
whatIndex 3 [0,1,2] == -1

Edit: Was able to get it to work.

Upvotes: 0

Views: 203

Answers (1)

Landei
Landei

Reputation: 54574

Of course you have Data.List.findIndex. If you want to write it yourself, there are plenty of ways, e.g.:

import Control.Monad

whatIndex x = msum . zipWith f [0..] where
  f i y = if x == y then Just i else Nothing

... which returns a Maybe Int. If you insist on your -1 hack, add fromMaybe (-1) $ (which comes from Data.Maybe) in front of msum.

Upvotes: 2

Related Questions