Sat Jul 23 17:08:37 CEST 2011


I need to distinguish two features:

  - representation of typed terms

  - terms implementing Num class

Will that work, or am I trying to stack incompatible parts?  I.e. a
Num instance "blesses" a datatype.  Can the final representation be a
data type, or is it a class?

Let's just try.

Fantastic.  It's still possible to use Num classes for the abstract syntax!

type Tfloat = Double
type Tint   = Integer

-- Class represents syntax, instances represent semantics.
class Symantics repr where
  int   :: Tint   -> repr Tint
  float :: Tfloat -> repr Tfloat
  addi  :: repr Tint   -> repr Tint   -> repr Tint
  addf  :: repr Tfloat -> repr Tfloat -> repr Tfloat

-- Interpretation 1: terms
data Term a = Int   a
            | Float a
            | Addi (Term a) (Term a)
            | Addf (Term a) (Term a)
            deriving (Show, Eq)

instance Symantics Term where
  int   = Int
  float = Float
  addi  = Addi
  addf  = Addf

-- Allow (Symantics repr) => Num (repr Tint)
instance (Show (repr Tint), Eq (repr Tint), Symantics repr) => Num (repr Tint) where
  (+) = addi
  fromInteger = int  
  -- Left out dummies

f a = a + a 

This gives:

> :t f
f :: (Num a) => a -> a

> f (int 1) :: Term Tint
Addi (Int 1) (Int 1)