[mercury-users] returning a term from a function? how to?
David Overton
dmo at cs.mu.OZ.AU
Thu May 3 14:06:55 AEST 2001
On Wed, May 02, 2001 at 08:32:24PM -0700, Terrence Brannon wrote:
> the following program works! and I did it all by myself! however,
Congratulations!
>
> 1 - I used an in,in,out predicate, where I would have preferred a function:
>
> :- pred add(rational,rational,rational).
> :- mode add( in , in , out).
> add(rational(N1,D1),rational(N2,D2),rational(NA,DA)) :-
> DA = D1 * D2,
> NA = N1 * D2 + N2 * D1.
>
> main -->
> { add(rational(1,3),rational(2,5),rational(A,B)) },
>
>
> because I do not know
> a - how to notate (declare) such a function
> b - how to write such a function
A direct translation into a function would be:
:- func add(rational,rational) = rational.
:- mode add( in , in ) = out.
add(rational(N1,D1),rational(N2,D2)) = rational(NA,DA) :-
DA = D1 * D2,
NA = N1 * D2 + N2 * D1.
which is a trivial transformation of the predicate version, but you
can write it more compactly by leaving out the mode declaration and
using a bit of functional notation:
:- func add(rational, rational) = rational.
add(rational(N1, D1), rational(N2, D2)) =
rational(N1 * D2 + N2 * D1, D1 * D2).
> c - how to write code to get back such a term from a function
Again, a simple transformation from the predicate version:
main -->
{ rational(A,B) = add(rational(1,3),rational(2,5)) },
io__write_int(A),nl,
io__write_string("-"),nl,
io__write_int(B).
David
--
David Overton Department of Computer Science & Software Engineering
PhD Student The University of Melbourne, Victoria 3010, Australia
+61 3 8344 9159 http://www.cs.mu.oz.au/~dmo
--------------------------------------------------------------------------
mercury-users mailing list
post: mercury-users at cs.mu.oz.au
administrative address: owner-mercury-users at cs.mu.oz.au
unsubscribe: Address: mercury-users-request at cs.mu.oz.au Message: unsubscribe
subscribe: Address: mercury-users-request at cs.mu.oz.au Message: subscribe
--------------------------------------------------------------------------
More information about the users
mailing list