Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell- find element in a list

Tags:

haskell

I want to write a function that takes a number i and a list of numbers xs and returns the position of i in the list xs, counting the first position as 1. If i does not occur in xs, then position returns 0.

So far I have this:

import Data.List
position :: Int -> [Int] -> Int
position i xs 
   | i `elem` xs = i `elemIndex` xs
   | otherwise = 0

But when I compile, it gives the following error:

Couldn't match expected type ‘Int’ with actual type ‘Maybe Int’

I know that elemIndex returns a Maybe Int type and I defined my function to return Int but I don't know how to change it. Any ideas?

like image 999
Diana Avatar asked Sep 14 '25 08:09

Diana


1 Answers

First of all, lists are indexed with 0…. So elemIndex will return Just 0 if i happens to be the first element of your list.

Since elemIndex returns Maybe Int, you could pattern match on its result instead:

import Data.List (elemIndex)

position :: Eq a => a -> [a] -> Int
position i xs =
    case i `elemIndex` xs of
       Just n  -> n + 1
       Nothing -> 0
like image 66
Zeta Avatar answered Sep 17 '25 04:09

Zeta