Created
January 31, 2014 22:00
-
-
Save nvanderw/8744144 to your computer and use it in GitHub Desktop.
Typeclasses as datatypes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- 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