Advertisement
Guest User

example generic class

a guest
Oct 29th, 2014
280
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. {-# LANGUAGE DeriveGeneric, DefaultSignatures #-}
  2. {-# LANGUAGE TypeOperators #-}
  3. {-# LANGUAGE FlexibleContexts, FlexibleInstances #-}
  4. {-# LANGUAGE ScopedTypeVariables, RankNTypes #-}
  5. import Generics.Deriving
  6.  
  7.  
  8. -- no value implies no default value
  9. -- instance Default' V1 where
  10.  
  11. -- no fields to default
  12. instance Default' U1 where
  13.  def' = U1
  14. -- default on this field
  15. instance (Default a) => Default' (K1 R a) where
  16.  def' = K1 def
  17. -- default recursively on each field
  18. instance (Default' f, Default' g) => Default' (f :*: g) where
  19.  def' = def' :*: def'
  20.  
  21. instance (Default' f) => Default' (M1 S s f) where
  22.   def' = M1 def'
  23. instance (Default' f) => Default' (M1 C c f) where
  24.   def' = M1 def'
  25. -- the leftmost term is the first constructor
  26. instance (Default' f) => Default' (f :+: g) where
  27.   def' = L1 def' -- order is guaranteed, nesting is not guaranteed
  28. instance (Default' f) => Default' (M1 D t f) where
  29.   def' = M1 def'
  30.  
  31.  
  32. class Default' f where
  33.  def' :: f a
  34.  
  35.  
  36. class Default a where
  37.   def :: a
  38.  
  39.   default def :: (Generic a, Default' (Rep a)) => a
  40.  def = to (def' :: Rep a x)
  41.  
  42.  
  43. data X = A Integer String | B Bool  deriving (Generic, Show)
  44. instance Default X
  45. instance Default Integer where def = 0
  46. instance Default String
  47.  
  48. main = do
  49.  print $ (def :: X)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement