[mercury-users] returning a term from a function? how to?

Terrence Brannon princepawn at earthlink.net
Thu May 3 13:32:24 AEST 2001


the following program works! and I did it all by myself! however, 

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
 c - how to write code to get back such a term from a function

question 2 - something tells me my type declaration below is
useless... hmm. Actually, no, I take that back, because I typed add/3
as rational,rational,rational, it is using my type definition to
expand and type that.

Entire program included for reference (and boasting).

:- module rational.
:- interface.
:- import_module io.

:- pred main(io__state::di, io__state::uo) is det.

:- implementation.
:- import_module std_util, int, list, bool, string.

:- type rational --->
	rational(numerator   :: int,
	         denominator :: int).

:- 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)) },
	  io__write_int(A),nl,
	  io__write_string("-"),nl,
	  io__write_int(B).



--------------------------------------------------------------------------
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