user8314628
user8314628

Reputation: 2042

Why do we constraint the input to Ord in the replicate function?

This is an example to rewrite the repeat function:

replicate' :: (Num i, Ord i) => i -> a -> [a]  
replicate' n x  
    | n <= 0    = []  
    | otherwise = x:replicate' (n-1) x

We only need to know how many times we are going to repeat the input. Why do we constraint the repeat number to be Ord? We don't care about the ordering, isn't it?

Upvotes: 0

Views: 57

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477210

If we look at the code, we see:

replicate' :: (Num i, Ord i) => i -> a -> [a]  
replicate' n x  
    | n <= 0    = []  
    | otherwise = x:replicate' (n-1) x

We thus check if n is less than or equal to 0. We thus need an order relation for n since this defines when two elements of type i are ordered in such way that the former is less than or equal to the latter.

This function is one offered by the Ord typeclass:

class Eq a => Ord a where
    compare :: a -> a -> Ordering
    (<) :: a -> a -> Bool
    (<=) :: a -> a -> Bool
    (>) :: a -> a -> Bool
    (>=) :: a -> a -> Bool
    max :: a -> a -> a
    min :: a -> a -> a

Implementing compare or (<=) is however enough, since all other functions can be derived from implementing one of these two (in fact implementing one of the (<), (<=), (>), and (>=) would in theory be sufficient, but here they opted to pick (<=) as implementation to derive from.

Upvotes: 2

Related Questions