[clean-list] Passing an environment around

Hamilton Richards ham@cs.utexas.edu
Wed, 18 Oct 2000 11:29:15 -0500


At 5:12 AM -0200 10/18/00, Jos=E9 Romildo Malaquias wrote:
>Hello.
>
>I am implementing a Computer Algebra system (CALG) in Clean, and I have a
>problem I would like the opinion of Clean programmers.
>
[...]
>
>Let's take an example: the algorithm for addition will have two arguments t=
o
>be added and a third argument corresponding to the enviroment:
>
>   add :: Expr Expr Env -> Expr
>
>and its result will depend of the flags in the environment. But it is highl=
y
>desirable to define functions like add as BINARY INFIX OPERATORS. Having 3
>arguments, add cannot be made a binary operator!
>
>  --------------------------------------------------------------------
>  So I am looking for alternative ways to pass the environment around.
>  --------------------------------------------------------------------
[...]

>
>Would be other good alternatives to solve this problem?

Perhaps it would help to distinguish between (1) "the algorithm for
addition" and (2) the transformation of expressions involving addition. If
I don't misunderstand your problem, the environment is needed for the
transformation, and not for the addition.

Consider representing your expressions as elements of a recursive algebraic
type. For example (please excuse the Haskell syntax),

	data Expr =3D Lit (Maybe Float) | Var String | Add Expr Expr |
	            Sub Expr Expr | Mul Expr Expr | Pow Expr Expr

Then the expression

	a^2 + b^2 + 3*a*b - a*b

would be represented by

	Sub (Add (Add (Pow "a" 2) (Pow "b" 2)) (Mul (Mul 3 "a") "b"))
            (Mul "a" "b")

and translating ordinary infix expressions to instances of Expr is routine.

Then you'll have functions such as

	transform :: Expr Env -> Expr  -- uses the environment

	evaluate :: Expr -> Maybe Float  -- uses the algorithm for addition

and the issue of the arity of infix operators never arises.

Hope that helps,

--HR



------------------------------------------------------------------
Hamilton Richards, PhD           Department of Computer Sciences
Senior Lecturer                  Mail Code C0500
512-471-9525                     The University of Texas at Austin
Taylor Hall 5.138                Austin, Texas 78712-1188
ham@cs.utexas.edu
------------------------------------------------------------------