Marcelo Mancini
Marcelo Mancini

Reputation: 23

Getting the index of the first occurrence of a given element in a given list

I am trying to implement the following specification:

busca.v.xs = <Min i : 0 ≤ i < #xs ∧ xs.i = v : i>

I wrote something like the following.

busca :: Int -> [Int] -> Int

busca v [] = 1000000
busca v (x:xs) | x==v = min x (busca v xs)
               | otherwise = busca v xs

When I was deriving, the case [] is infinity, so I tried making something that is somewhat similar. The expected result should be the minimun number in a list. For example, busca 2 [4,3,2,2,7] should return 2. Can i use Maybe and simulate that infinity in a way?

Upvotes: 0

Views: 287

Answers (1)

Daniel Wagner
Daniel Wagner

Reputation: 152682

You could make a fresh type for which min did what you ask like this:

data PosInfty a = Finite a | Infinite deriving (Eq, Ord, Read, Show)

Derived Ord instances treat values made with earlier constructors as unconditionally smaller than values made with later constructors, so all Finite values will be less than Infinite.

This type is also available (with significantly more instances) from monoid-extras.

Upvotes: 3

Related Questions