Advertisement
00dani

UtilityClass.hs

Feb 2nd, 2021
1,791
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. {-# LANGUAGE FlexibleInstances, UndecidableInstances #-}
  2. data LinkedList a = Cons a (LinkedList a) | End deriving Show
  3. data PairList a = Pair a a (PairList a) | PairEnd deriving Show
  4.  
  5. class List a where
  6.   len :: a -> Integer
  7.  
  8. instance List (LinkedList a) where
  9.   len End = 0
  10.   len (Cons _ xs) = 1 + len xs
  11.  
  12. instance List (PairList a) where
  13.   len PairEnd = 0
  14.   len (Pair _ _ xs) = 2 + len xs
  15.  
  16. class List a => Reverse a where
  17.   rev :: a -> a
  18.  
  19. instance {-# OVERLAPPABLE #-} List a => Reverse a where
  20.   rev = id
  21.  
  22. instance Reverse (PairList a) where
  23.   rev (Pair x y ys) = Pair y x (rev ys)
  24.   rev PairEnd = PairEnd
  25.  
  26. main = do
  27.   let linkedList = Cons 1 (Cons 2 End)
  28.   print linkedList
  29.   print $ rev linkedList
  30.   let pairList = Pair 1 2 (Pair 3 4 PairEnd)
  31.   print pairList
  32.   print $ rev pairList
  33.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement