0

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.

8
  • 1
    Are you familiar with the concept of an accumulator? A worker function (often named go)? Commented Feb 13, 2013 at 2:57
  • I understand the concept of an accumulator, but not a worker function. Commented Feb 13, 2013 at 3:00
  • what is the problem? what would you like to happen when the element is not in the list? Commented Feb 13, 2013 at 3:01
  • @KelseyAbreu Often when something may fail (as in, not finding the element) the function will return Maybe. Commented Feb 13, 2013 at 3:03
  • 11
    @KelseyAbreu If you answered your own question, you should post what you discovered as an answer, and accept that answer as correct. The goal of StackOverflow is only in part to answer questions; the other part is to create an artifact that is useful for future visitors with similar questions. Commented Feb 13, 2013 at 4:32

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.