'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?



Solution 1:[1]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Daniel Wagner