[Haskell-cafe] Elementary question about Type Constraints

Malte Milatz malte at gmx-topmail.de
Mon Jul 9 15:20:08 EDT 2007


(Sorry, wrong button again when sending this the first time.)

lassoken:
> data Term b = Var String | Const b | Sum (Term b) (Term b) | Prod
> (Term b) (Term b) 
> 
> newSum (Const a) (Const b) = Const (a+b)
> newSum (Const 0) t at _ = t
> newSum t at _ (Const 0) = t
> newSum a b = Sum a b
 
Is there any reason to use t at _ instead of just t? If there is, please
tell me!

> --instance Show (Term b) where show = showTerm
> showTerm (Var x) = x 
> showTerm (Const c) = show c
> showTerm (Sum a b) = "(" ++ showTerm a ++ "+" ++ showTerm b ++ ")"
> showTerm (Prod a b) = "(" ++ showTerm a ++ showTerm b ++ ")"
> --- 
> 
> Where should I put type constraint (Show b) to be able to define Term
> b as an instance of Show class? 

The syntax is

	instance (Show b) => Show (Term b) where ...

> Actually, I would like to say that Term b is an instance of Show iff b
> is and not to put constraint on b. 
> 
That's exactly what the constraint (Show b) above does.  The arrow can
be read as in maths (»implies«), so it corresponds to the »iff« in your
sentence.

By the way, the following implementation should be more efficient on
very large data (if I have understood the corresponding chapter in the
Haskell School of Expression correctly):

	instance (Show b) => Show (Term b) where
	        show x = showTerm x ""

	showTerm (Var x)    = showString x
	showTerm (Const c)  = shows c
	showTerm (Sum a b)  = showChar '(' . showTerm a . showChar '+' .
				showTerm b . showChar ')'
	showTerm (Prod a b) = showChar '(' . showTerm a . showTerm b . 
				showChar ')'

Malte



More information about the Haskell-Cafe mailing list