Skip to content

Instantly share code, notes, and snippets.

@nvanderw
Created January 31, 2014 22:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nvanderw/8744144 to your computer and use it in GitHub Desktop.
Save nvanderw/8744144 to your computer and use it in GitHub Desktop.
Typeclasses as datatypes
-- Standard Prelude definitions
-- data Ordering = LT | EQ | GT
-- class Eq a => Ord a where
-- compare :: a -> a -> Ordering
isOrdered :: Ord a => [a] -> Bool
isOrdered (x:y:xs) = case compare x y of
GT -> False
_ -> isOrdered (y:xs)
isOrdered _ = True
-- isOrdered [1,2,3] = True
-- isOrdered [3,3,1] = False
-- *But* we could also define a datatype for the "Ord" typeclass, and pass
-- the instances as arguments.
newtype Ord' a = Ord' (a -> a -> Ordering)
isOrdered' :: Ord' a -> [a] -> Bool
isOrdered' c@(Ord' compare) (x:y:xs) = case compare x y of
GT -> False
_ -> isOrdered' c (y:xs)
isOrdered' _ _ = True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment