[mercury-users] Maths and contexts.

Peter Ross pro at missioncriticalit.com
Fri Apr 20 17:03:51 AEST 2012


On 20 April 2012 07:25, Michael Richter <ttmrichter at gmail.com> wrote:
> And here's the problem: how do I associate a given calculation with a
> calculation context?  Just passing it in as a parameter is a non-starter
> because these are the implementation functions.  The exposed API will be,
> shockingly, "+" for add/2, "/" for divide/2, etc.  So while it would be easy
> to do divide(1, 3, MyContext) in code, that's not really an acceptable
> solution because I can't do 1 / 3 (MyContext) (or whatever).  "/" (and other
> mathematical operations' predicates/functions) is militantly outfitted with
> an arity of 2.
>
The key point for me is that a context is associated with an
expression that needs to be evaluated, so it's not at the level of the
operator but of the expression as a whole.

So define a type expr which in my case will operate on numbers which
are integers.

:- type num == int.
:- type expr ---> n(num) ; expr + expr ; expr * expr.

now you have to evaluate the above expression in some context and the
result will be a num.

:- func evaluate(context, expr) = num.

evaluate(_, n(Num)) = Num.

evaluate(Context, A + B) = Num :-
    NumA = evaluate(Context, A),
    NumB = evaluate(Context, B),
    Num = add(Context, NumA, NumB).

evaluate(Context, A * B) = Num :-
    NumA = evaluate(Context, A),
    NumB = evaluate(Context, B),
    Num = multiply(Context, NumA, NumB).

Now if we want to use it

Num = evaluate(context, n(4) + n(5) * n(3)).

The annoying thing is have to wrap each of our numbers in a n().  Note
the associativity and precedence of + * is handled for you
automatically by the parser.

Hope that helps,
Pete

--------------------------------------------------------------------------
mercury-users mailing list
Post messages to:       mercury-users at csse.unimelb.edu.au
Administrative Queries: owner-mercury-users at csse.unimelb.edu.au
Subscriptions:          mercury-users-request at csse.unimelb.edu.au
--------------------------------------------------------------------------



More information about the users mailing list