Algebraic Expression Languages   [6]

Variations in syntactic style and semantic domain

Once we have abstracted out the structure from both the data type and the fold, it is especially easy to vary the details of the syntactic representation and/or semantic domains we use for expressions. As mentioned before, we could reasonably use strings, lists of digits, Peano numerals, Ints or Integers for the representation of literals. We might also use strings, characters or values of an enumerated type for operators. If we use meta-language integers for the literals, it might be considered reasonable to use meta-language functions to represent the operators: then the fold required to evaluate the expressions is just fold id id!

{ Semantics in numerals (rather than integers). Semantics in other numeric types. }

This flexibility and the plethora of options raises the question of what counts as a representation (syntax) and what counts as meaning (semantics): there is no straightforward answer to this question (perhaps the distinction between the two is only a red herring), but we can sketch out some of the issues:

type AExp0 = Expr Int AOp

eval0 = fold id  sem  where sem Add = (+) ; sem Mul = (*)

-----

type AExp1 = Expr Nat AOp

eval1 = fold id  sem  where sem Add = add ; sem Mul = mul

-- here "add" and "mul" are the iterative algorithms on Nats

-----

type AExp2 = Expr String String

eval2 = fold num sem  where sem "+" = (+) ; sem "*" = (*)

-----

type AExp3 = Expr Int AOp  -- semantics as [Bit]

eval2 = fold bits sem  where sem Add = addbs ; sem Mul = mulbs

-----

prt  = fold show (inf . syn)

syn Add = "+"
syn Mul = "*"

inf o l r = par (unwords [l, o, r])
par s = "(" ++ s ++ ")"

Notes