[mercury-users] Det/Semidet
Julien Fischer
juliensf at csse.unimelb.edu.au
Mon Dec 11 12:45:07 AEDT 2006
On Fri, 8 Dec 2006, Nigel Evans wrote:
> I am new to mercury and i am having a problem with determinism. I know main
> cannot be semidet, but how can i switch the code around so that the
> following example compiles? Any help would be greatly appreciated.
The usual mechansim for interfacing semidet code with det code is to
place the semidet code in the condition of an if-then-else. In this
particular case that is unecessary though.
> :- module marray.
> :- interface.
>
> :- import_module io.
>
> :- pred main(io::di, io::uo) is det.
>
> :- implementation.
>
> :- import_module list, string, array2d, int.
>
> main(!IO) :-
> new(5,5,["XXX"]) = MyArray,
> MyList = ["the","cat","chased","the","dog"],
> add_input_string(MyList,MyArray, 0).
>
>
> :- pred add_input_string(list(string)::in,
> array2d(list(string))::array2d_di, int::in) is semidet.
> add_input_string(TheList, Array, Number) :-
> TheList = [Head|Tail],
> ( Array ^ elem(0,Number) := [Head] ) = T3,
> NextNumber is Number + 1,
In Mercury this would usually just be written as:
NextNumber = Number + 1,
> add_input_string(Tail,T3,NextNumber).
The above program can be written completely deterministically. (I've
modified it slightly so that add_input_string/3 returns the updated
array and main/2 prints it out.)
:- module marray.
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.
:- implementation.
:- import_module array2d.
:- import_module int.
:- import_module list.
:- import_module string.
main(!IO) :-
MyArray0 = array2d.new(5, 5, ["XXX"]),
MyList = ["the", "cat", "chased", "the", "dog"],
add_input_string(MyList, 0, MyArray0, MyArray),
io.write(MyArray, !IO).
:- pred add_input_string(list(string)::in, int::in,
array2d(list(string))::array2d_di,
array2d(list(string))::array2d_uo) is det.
add_input_string([], _, !Array).
add_input_string([ Head | Tail ], Num0, !Array) :-
!:Array = !.Array ^ elem(0, Num0) := [Head],
Num = Num0 + 1,
add_input_string(Tail, Num, !Array).
Julien.
--------------------------------------------------------------------------
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