[m-rev.] diff: further samples directory cleanups

Julien Fischer juliensf at csse.unimelb.edu.au
Mon Jan 10 13:29:07 AEDT 2011


Branches; main, 11.01

samples/*.m:
 	Further code and formatting cleanups.  There are no changes
 	to any algorithms.

Julien.

Index: calculator.m
===================================================================
RCS file: /home/mercury/mercury1/repository/mercury/samples/calculator.m,v
retrieving revision 1.12
diff -u -r1.12 calculator.m
--- calculator.m	21 Mar 2006 00:50:57 -0000	1.12
+++ calculator.m	10 Jan 2011 02:27:22 -0000
@@ -1,50 +1,66 @@
+%-----------------------------------------------------------------------------%
+% vim: ft=mercury ts=4 sw=4 et
+%-----------------------------------------------------------------------------%
+%
  % A simpler calculator - parses and evaluates integer expressions.
-
+%
  % For an example of a parser with better error handling, see parser.m in
  % the Mercury library source code.
-
+%
  % Author: fjh.
-
+%
  % This source file is hereby placed in the public domain.  -fjh.
+%
+%-----------------------------------------------------------------------------%

  :- module calculator.
  :- interface.
+
  :- import_module io.

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

+%-----------------------------------------------------------------------------%
+%-----------------------------------------------------------------------------%
+
  :- implementation.
-:- import_module list, char, int, string.
+
+:- import_module char.
+:- import_module int.
+:- import_module list.
+:- import_module string.
+
+%-----------------------------------------------------------------------------%

  :- type expr
-	--->	number(int)
-	;	plus(expr, expr)
-	;       minus(expr, expr)
-	;       times(expr, expr)
-	;       div(expr, expr).
+    --->    number(int)
+    ;       plus(expr, expr)
+    ;       minus(expr, expr)
+    ;       times(expr, expr)
+    ;       div(expr, expr).

  main(!IO) :-
-	io.write_string("calculator> ", !IO),
-	io.flush_output(!IO),
-	io.read_line(Res, !IO),
-	(
-		Res = error(_),
-		io.write_string("Error reading from stdin\n", !IO)
-	;
-		Res = eof,
-		io.write_string("EOF\n", !IO)
-	;
-		Res = ok(Line0),
-		list.delete_all(Line0, ' ', Line),
-		( fullexpr(X, Line, []) ->
-			Num = evalexpr(X),
-			io.write_int(Num, !IO),
-			io.write_string("\n", !IO)
-		;
-			io.write_string("Syntax error\n", !IO)
-		),
-		main(!IO) % recursively call ourself for the next line(s)
-	).
+    io.write_string("calculator> ", !IO),
+    io.flush_output(!IO),
+    io.read_line(Res, !IO),
+    (
+        Res = error(_),
+        io.write_string("Error reading from stdin\n", !IO)
+    ;
+        Res = eof,
+        io.write_string("EOF\n", !IO)
+    ;
+        Res = ok(Line0),
+        list.delete_all(Line0, ' ', Line),
+        ( fullexpr(X, Line, []) ->
+            Num = evalexpr(X),
+            io.write_int(Num, !IO),
+            io.write_string("\n", !IO)
+        ;
+            io.write_string("Syntax error\n", !IO)
+        ),
+        main(!IO) % recursively call ourself for the next line(s)
+    ).

  :- func evalexpr(expr) = int.

@@ -59,61 +75,65 @@
  :- pred fullexpr(expr::out, list(char)::in, list(char)::out) is semidet.

  fullexpr(X) -->
-	expr(X),
-	['\n'].
+    expr(X),
+    ['\n'].

  :- pred expr(expr::out, list(char)::in, list(char)::out) is semidet.

  expr(Expr) -->
-	factor(Factor),
-	expr2(Factor, Expr).
+    factor(Factor),
+    expr2(Factor, Expr).

  :- pred expr2(expr::in, expr::out, list(char)::in, list(char)::out) is semidet.

  expr2(Factor, Expr) -->
-	( ['+'] -> factor(Factor2), expr2(plus( Factor, Factor2), Expr)
-	; ['-'] -> factor(Factor2), expr2(minus(Factor, Factor2), Expr)
-	; { Expr = Factor }
-	).
+    ( ['+'] -> factor(Factor2), expr2(plus( Factor, Factor2), Expr)
+    ; ['-'] -> factor(Factor2), expr2(minus(Factor, Factor2), Expr)
+    ; { Expr = Factor }
+    ).

  :- pred factor(expr::out, list(char)::in, list(char)::out) is semidet.

  factor(Factor) -->
-	term(Term),
-	factor2(Term, Factor).
+    term(Term),
+    factor2(Term, Factor).

  :- pred factor2(expr::in, expr::out, list(char)::in, list(char)::out)
-	is semidet.
+    is semidet.

  factor2(Term, Factor) -->
-	( ['*'] -> term(Term2), factor2(times(Term, Term2), Factor)
-	; ['/'] -> term(Term2), factor2(div(  Term, Term2), Factor)
-	; { Factor = Term }
-	).
+    ( ['*'] -> term(Term2), factor2(times(Term, Term2), Factor)
+    ; ['/'] -> term(Term2), factor2(div(  Term, Term2), Factor)
+    ; { Factor = Term }
+    ).

  :- pred term(expr::out, list(char)::in, list(char)::out) is semidet.

  term(Term) -->
-	( const(Const) ->
-		{ string.from_char_list(Const, ConstString) },
-		{ string.to_int(ConstString, Num) },
-		{ Term = number(Num) }
-	;
-		['('], expr(Term), [')']
-	).
+    ( const(Const) ->
+        { string.from_char_list(Const, ConstString) },
+        { string.to_int(ConstString, Num) },
+        { Term = number(Num) }
+    ;
+        ['('], expr(Term), [')']
+    ).

  :- pred const(list(char)::out, list(char)::in, list(char)::out) is semidet.

  const([Digit|Rest]) -->
-	digit(Digit),
-	( const(Const) ->
-		{ Rest = Const }
-	;
-		{ Rest = [] }
-	).
+    digit(Digit),
+    ( const(Const) ->
+        { Rest = Const }
+    ;
+        { Rest = [] }
+    ).

  :- pred digit(char::out, list(char)::in, list(char)::out) is semidet.

  digit(Char) -->
-	[Char],
-	{ char.is_digit(Char) }.
+    [Char],
+    { char.is_digit(Char) }.
+
+%-----------------------------------------------------------------------------%
+:- end_module calculator.
+%-----------------------------------------------------------------------------%
Index: calculator2.m
===================================================================
RCS file: /home/mercury/mercury1/repository/mercury/samples/calculator2.m,v
retrieving revision 1.6
diff -u -r1.6 calculator2.m
--- calculator2.m	4 Apr 2008 03:58:44 -0000	1.6
+++ calculator2.m	10 Jan 2011 02:27:22 -0000
@@ -1,5 +1,7 @@
+%-----------------------------------------------------------------------------%
  % vim: ft=mercury ts=4 sw=4 et
-
+%-----------------------------------------------------------------------------%
+%
  % Another calculator - parses and evaluates integer expression terms.
  % This module demonstrates the use of user-defined operator precedence
  % tables with parser.read_term.
@@ -8,15 +10,21 @@
  % This version also allows variable assignments of the form `X = Exp.'.
  %
  % Author: stayl.
-
+%
  % This source file is hereby placed in the public domain.  -stayl.
+%
+%-----------------------------------------------------------------------------%

  :- module calculator2.
  :- interface.
+
  :- import_module io.

  :- pred main(io::di, io::uo) is cc_multi.

+%-----------------------------------------------------------------------------%
+%-----------------------------------------------------------------------------%
+
  :- implementation.

  :- import_module exception.
@@ -34,6 +42,8 @@
  :- import_module univ.
  :- import_module varset.

+%-----------------------------------------------------------------------------%
+
  :- type calc_info == map(string, int).

  main(!IO) :-
@@ -221,3 +231,7 @@
      ops.max_priority(_) = 700,
      ops.arg_priority(Table) = ops.max_priority(Table) + 1
  ].
+
+%-----------------------------------------------------------------------------%
+:- end_module calculator2.
+%-----------------------------------------------------------------------------%
Index: cat.m
===================================================================
RCS file: /home/mercury/mercury1/repository/mercury/samples/cat.m,v
retrieving revision 1.7
diff -u -r1.7 cat.m
--- cat.m	12 Aug 2005 04:50:36 -0000	1.7
+++ cat.m	10 Jan 2011 02:27:22 -0000
@@ -1,84 +1,94 @@
  %-----------------------------------------------------------------------------%
-
-:- module cat.
-
+% vim: ft=mercury ts=4 sw=4 et
+%-----------------------------------------------------------------------------%
+%
  % Simple implementation of the standard unix `cat' filter:
  % copy input files (or stdin, if no input files) to stdout.
-
+%
  % This source file is hereby placed in the public domain.  -fjh (the author).
-
+%
  %-----------------------------------------------------------------------------%

+:- module cat.
  :- interface.
+
  :- import_module io.

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

  %-----------------------------------------------------------------------------%
+%-----------------------------------------------------------------------------%

  :- implementation.
-:- import_module string, list, char.
+
+:- import_module char.
+:- import_module list.
+:- import_module string.
+
+%-----------------------------------------------------------------------------%

  main(!IO) :-
-	io.command_line_arguments(Args, !IO),
-	( Args = [] ->
-		cat(!IO)
-	;
-		cat_file_list(Args, !IO)
-	).
+    io.command_line_arguments(Args, !IO),
+    (
+        Args = [],
+        cat(!IO)
+    ;
+        Args = [_ | _],
+        cat_file_list(Args, !IO)
+    ).

  :- pred cat_file_list(list(string)::in, io::di, io::uo) is det.

  cat_file_list([], !IO).
  cat_file_list([File | Files], !IO) :-
-	cat_file(File, !IO),
-	cat_file_list(Files, !IO).
+    cat_file(File, !IO),
+    cat_file_list(Files, !IO).

  :- pred cat_file(string::in, io::di, io::uo) is det.

  cat_file(File, !IO) :-
-	io.open_input(File, Result, !IO),
-	(
-		Result = ok(Stream),
-		cat_stream(Stream, !IO),
-		io.close_input(Stream, !IO)
-	;
-		Result = error(Error),
-		io.progname("cat", Progname, !IO),
-		io.error_message(Error, Message),
-		io.write_strings([
-			Progname, ": ",
-			"error opening file `", File, "' for input:\n\t",
-			Message, "\n"
-		], !IO)
-	).
+    io.open_input(File, Result, !IO),
+    (
+        Result = ok(Stream),
+        cat_stream(Stream, !IO),
+        io.close_input(Stream, !IO)
+    ;
+        Result = error(Error),
+        io.progname("cat", Progname, !IO),
+        io.error_message(Error, Message),
+        io.write_strings([
+            Progname, ": ",
+            "error opening file `", File, "' for input:\n\t",
+            Message, "\n"
+        ], !IO)
+    ).

  :- pred cat_stream(io.input_stream::in, io::di, io::uo) is det.

  cat_stream(Stream, !IO) :-
-	io.set_input_stream(Stream, _OldStream, !IO),
-	cat(!IO).
+    io.set_input_stream(Stream, _OldStream, !IO),
+    cat(!IO).

  :- pred cat(io::di, io::uo) is det.

  cat(!IO) :-
-	io.read_line_as_string(Result, !IO),
-	(
-		Result = ok(Line),
-		io.write_string(Line, !IO),
-		cat(!IO)
-	;
-		Result = eof
-	;
-		Result = error(Error),
-		io.error_message(Error, Message),
-		io.input_stream_name(StreamName, !IO),
-		io.progname("cat", ProgName, !IO),
-		io.write_strings([
-			ProgName, ": ",
-			"error reading input file `", StreamName, "': \n\t",
-			Message, "\n"
-		], !IO)
-	).
+    io.read_line_as_string(Result, !IO),
+    (
+        Result = ok(Line),
+        io.write_string(Line, !IO),
+        cat(!IO)
+    ;
+        Result = eof
+    ;
+        Result = error(Error),
+        io.error_message(Error, Message),
+        io.input_stream_name(StreamName, !IO),
+        io.progname("cat", ProgName, !IO),
+        io.write_strings([
+            ProgName, ": ",
+            "error reading input file `", StreamName, "': \n\t",
+            Message, "\n"
+        ], !IO)
+    ).

  %-----------------------------------------------------------------------------%
Index: e.m
===================================================================
RCS file: /home/mercury/mercury1/repository/mercury/samples/e.m,v
retrieving revision 1.6
diff -u -r1.6 e.m
--- e.m	21 Mar 2006 00:50:57 -0000	1.6
+++ e.m	10 Jan 2011 02:27:22 -0000
@@ -1,19 +1,21 @@
  %-----------------------------------------------------------------------------%
+% vim: ft=mercury ts=4 sw=4 et
  %-----------------------------------------------------------------------------%
-
+%
  % File: e.m.
  % Main author: bromage.
-
+%
  % This source file is hereby placed in the public domain.  -bromage.
-
+%
  % Calculate the base of natural logarithms using lazy evaluation.
-
+%
  % The algorithm is O(N^2) in the number of digits requested.
-
+%
  %-----------------------------------------------------------------------------%

  :- module e.
  :- interface.
+
  :- import_module io.

  :- pred main(io::di, io::uo) is det.
@@ -29,47 +31,49 @@
  :- import_module require.
  :- import_module string.

-	% Default number of digits displayed (if this is not specified
-	% on the command line).
-	%
+%-----------------------------------------------------------------------------%
+
+    % Default number of digits displayed (if this is not specified
+    % on the command line).
+    %
  :- func default_digits = int.
  default_digits = 1000.

-	% Change this for a base other than 10.  Any integer between
-	% 2 and 36 makes sense.
-	%
+    % Change this for a base other than 10.  Any integer between
+    % 2 and 36 makes sense.
+    %
  :- func base = int.
  base = 10.

-	% Number of columns on the terminal.
-	%
+    % Number of columns on the terminal.
+    %
  :- func columns = int.
  columns = 78.

  %-----------------------------------------------------------------------------%

-	% This is a simple implementation of an infinite lazy stream.
-	%
+    % This is a simple implementation of an infinite lazy stream.
+    %
  :- type int_stream
-	--->	[int | int_stream]
-	;	closure((func) = int_stream).
+    --->    [int | int_stream]
+    ;   closure((func) = int_stream).

  :- inst int_stream ==
-	bound([ground | int_stream] ; closure((func) = is_out is det)).
+    bound([ground | int_stream] ; closure((func) = is_out is det)).

  :- mode is_in  == in(int_stream).
  :- mode is_out == out(int_stream).

  %-----------------------------------------------------------------------------%

-	% An infinite stream of ones.
-	% 
+    % An infinite stream of ones.
+    %
  :- func ones = (int_stream :: is_out) is det.

  ones = [1 | closure((func) = ones)].

-	% All the digits of e in one stream.
-	% 
+    % All the digits of e in one stream.
+    %
  :- func digits_of_e = (int_stream :: is_out) is det.

  digits_of_e = next_digit(ones).
@@ -77,68 +81,69 @@
  :- func next_digit(int_stream::is_in) = (int_stream::is_out) is det.

  next_digit(Stream0) = [Digit | closure((func) = next_digit(Stream))] :-
-	scale(2, Digit, Stream0, Stream).
+    scale(2, Digit, Stream0, Stream).

  :- pred scale(int::in, int::out, int_stream::is_in, int_stream::is_out) is det.

  scale(C, Digit, closure(Func), Stream) :-
-	scale(C, Digit, apply(Func), Stream).
+    scale(C, Digit, apply(Func), Stream).
  scale(C, Digit, [D | Ds], Stream) :-
-	K = base * D,
-	KdC = K // C,
-	( KdC = (K + base - 1) // C ->
-		% We have the next digit.  Construct a closure to
-		% generate the rest.
-
-		Digit = KdC,
-		Stream = closure((func) = [K rem C + NextDigit | Stream0] :-
-				scale(C + 1, NextDigit, Ds, Stream0)
-			)
-	;
-		% We have a carry to factor in, so calculate the next
-		% digit eagerly then add it on.
-
-		scale(C + 1, A1, Ds, B1),
-		Digit = (K + A1) // C,
-		Stream = [(K + A1) rem C | B1]
-	).
+    K = base * D,
+    KdC = K // C,
+    ( KdC = (K + base - 1) // C ->
+        % We have the next digit.  Construct a closure to
+        % generate the rest.
+
+        Digit = KdC,
+        Stream = closure((func) = [K rem C + NextDigit | Stream0] :-
+                scale(C + 1, NextDigit, Ds, Stream0)
+            )
+    ;
+        % We have a carry to factor in, so calculate the next
+        % digit eagerly then add it on.
+
+        scale(C + 1, A1, Ds, B1),
+        Digit = (K + A1) // C,
+        Stream = [(K + A1) rem C | B1]
+    ).

  %-----------------------------------------------------------------------------%
  %-----------------------------------------------------------------------------%

  main(!IO) :-
-	io.command_line_arguments(Args, !IO),
-	(
-		Args = [Arg | _],
-		string.to_int(Arg, Digits0)
-	->
-		Digits = Digits0
-	;
-		Digits = default_digits
-	),
-	string.int_to_base_string(2, base, BaseString),
-	io.write_strings([BaseString, "."], !IO),
-	string.length(BaseString, BaseStringLength),
-	main_2(Digits, columns - BaseStringLength - 1, digits_of_e, !IO),
-	io.nl(!IO).
+    io.command_line_arguments(Args, !IO),
+    (
+        Args = [Arg | _],
+        string.to_int(Arg, Digits0)
+    ->
+        Digits = Digits0
+    ;
+        Digits = default_digits
+    ),
+    string.int_to_base_string(2, base, BaseString),
+    io.write_strings([BaseString, "."], !IO),
+    string.length(BaseString, BaseStringLength),
+    main_2(Digits, columns - BaseStringLength - 1, digits_of_e, !IO),
+    io.nl(!IO).

-	% Print out digits until we don't have any more.
-	% 
+    % Print out digits until we don't have any more.
+    %
  :- pred main_2(int::in, int::in, int_stream::is_in, io::di, io::uo) is det.

-main_2(Digits, Columns, closure(Func), !IO) :- 
-	main_2(Digits, Columns, apply(Func), !IO).
+main_2(Digits, Columns, closure(Func), !IO) :- 
+    main_2(Digits, Columns, apply(Func), !IO).
  main_2(Digits, Columns, [I | Is], !IO) :-
-	( Digits = 0 ->
-		true
-	; Columns = 0 ->
-		io.nl(!IO),
-		main_2(Digits, columns, [I | Is], !IO)
-	;
-		char.det_int_to_digit(I, Digit),
-		io.write_char(Digit, !IO),
-		main_2(Digits - 1, Columns - 1, Is, !IO)
-	).
+    ( Digits = 0 ->
+        true
+    ; Columns = 0 ->
+        io.nl(!IO),
+        main_2(Digits, columns, [I | Is], !IO)
+    ;
+        char.det_int_to_digit(I, Digit),
+        io.write_char(Digit, !IO),
+        main_2(Digits - 1, Columns - 1, Is, !IO)
+    ).

  %-----------------------------------------------------------------------------%
+:- end_module e.
  %-----------------------------------------------------------------------------%
Index: eliza.m
===================================================================
RCS file: /home/mercury/mercury1/repository/mercury/samples/eliza.m,v
retrieving revision 1.19
diff -u -r1.19 eliza.m
--- eliza.m	28 Jun 2006 09:11:07 -0000	1.19
+++ eliza.m	10 Jan 2011 02:27:22 -0000
@@ -653,3 +653,7 @@
          no       - "Say, do you have any psychological problems?"
          ]
      ]).
+
+%-----------------------------------------------------------------------------%
+:- end_module eliza.
+%-----------------------------------------------------------------------------%
Index: expand_terms.m
===================================================================
RCS file: /home/mercury/mercury1/repository/mercury/samples/expand_terms.m,v
retrieving revision 1.5
diff -u -r1.5 expand_terms.m
--- expand_terms.m	21 Mar 2006 00:50:57 -0000	1.5
+++ expand_terms.m	10 Jan 2011 02:27:22 -0000
@@ -1,101 +1,112 @@
  %-----------------------------------------------------------------------------%
-
+% vim: ft=mercury ts=4 sw=4 et wm=0 tw=0
+%-----------------------------------------------------------------------------%
+%
  % Emulation of Prolog's expand_term/term_expansion mechanism.
  % This program provides pre-processing of Mercury programs,
  % using an arbitrary term-to-term translation given by the
  % `term_expansion' predicate.
-
+%
  % To use, copy this file to the directory containing your source code, and
  % modify the `term_expansion' predicate at the end of this file to provide your
  % own term expansion.  Then add
  %
-%	*.m: expand_terms
-%	%.m: %.m.in
-%		expand_terms $*.m.in > $*.m
+%   *.m: expand_terms
+%   %.m: %.m.in
+%       expand_terms $*.m.in > $*.m
  %
  % to your Mmake file, and rename your `.m' files with the suffix `.m.in'.
-
+%
  % This source file is hereby placed in the public domain.  -fjh (the author).
-
+%
  %-----------------------------------------------------------------------------%

  :- module expand_terms.
  :- interface.
+
  :- import_module io.

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

  %-----------------------------------------------------------------------------%
+%-----------------------------------------------------------------------------%

  :- implementation.
-:- import_module string, list, term, varset, term_io.
+
+:- import_module list.
+:- import_module string.
+:- import_module term.
+:- import_module term_io.
+:- import_module varset.
+
+%-----------------------------------------------------------------------------%

  main(!IO) :-
-	io.command_line_arguments(Args, !IO),
-	( 
-		Args = [],
-		expand_terms(!IO)
-	;
-		Args = [_ | _],
-		expand_terms_file_list(Args, !IO)
-	).
- 
+    io.command_line_arguments(Args, !IO),
+    ( 
+        Args = [],
+        expand_terms(!IO)
+    ;
+        Args = [_ | _],
+        expand_terms_file_list(Args, !IO)
+    ).
+
  :- pred expand_terms_file_list(list(string)::in, io::di, io::uo) is det.

  expand_terms_file_list([], !IO).
  expand_terms_file_list([File | Files], !IO) :-
-	expand_terms_file(File, !IO),
-	expand_terms_file_list(Files, !IO).
+    expand_terms_file(File, !IO),
+    expand_terms_file_list(Files, !IO).

  :- pred expand_terms_file(string::in, io::di, io::uo) is det.

  expand_terms_file(File, !IO) :-
-	io.open_input(File, Result, !IO),
-	( Result = ok(Stream),
-		expand_terms_stream(Stream, !IO)
-	; Result = error(Error),
-		io.progname("expand_terms", Progname, !IO),
-		io.error_message(Error, Message),
-		io.write_strings([
-			Progname, ": ",
-			"error opening file `", File, "' for input:\n\t",
-			Message, "\n"
-		], !IO),
-		io.set_exit_status(1, !IO)
-	).
+    io.open_input(File, Result, !IO),
+    ( Result = ok(Stream),
+        expand_terms_stream(Stream, !IO)
+    ; Result = error(Error),
+        io.progname("expand_terms", Progname, !IO),
+        io.error_message(Error, Message),
+        io.write_strings([
+            Progname, ": ",
+            "error opening file `", File, "' for input:\n\t",
+            Message, "\n"
+        ], !IO),
+        io.set_exit_status(1, !IO)
+    ).

  :- pred expand_terms_stream(io.input_stream::in, io::di, io::uo) is det.

  expand_terms_stream(Stream, !IO) :-
-	io.set_input_stream(Stream, _OldStream, !IO),
-	expand_terms(!IO).
+    io.set_input_stream(Stream, _OldStream, !IO),
+    expand_terms(!IO).

  :- pred expand_terms(io::di, io::uo) is det.

  expand_terms(!IO) :-
-	term_io.read_term(Result, !IO),
-	expand_terms_2(Result, !IO).
+    term_io.read_term(Result, !IO),
+    expand_terms_2(Result, !IO).

  :- pred expand_terms_2(read_term::in, io::di, io::uo) is det.

  expand_terms_2(Result, !IO) :-
-	(
-		Result = term(VarSet0, Term0),
-		expand_term(Term0, VarSet0, Term, VarSet),
-		term_io.write_term(VarSet, Term, !IO),
-		io.write_string(".\n", !IO),
-		term_io.read_term(NextResult, !IO),
-		expand_terms_2(NextResult, !IO)
-	;
-		Result = eof
-	;
-		Result = error(Message, LineNum),
-		io.input_stream_name(StreamName, !IO),
-		string.format("%s:%03d: %s\n", [s(StreamName), i(LineNum),
-			s(Message)], FullMessage),
-		io.write_string(FullMessage, !IO),
-		io.set_exit_status(1, !IO)
-	).
+    (
+        Result = term(VarSet0, Term0),
+        expand_term(Term0, VarSet0, Term, VarSet),
+        term_io.write_term(VarSet, Term, !IO),
+        io.write_string(".\n", !IO),
+        term_io.read_term(NextResult, !IO),
+        expand_terms_2(NextResult, !IO)
+    ;
+        Result = eof
+    ;
+        Result = error(Message, LineNum),
+        io.input_stream_name(StreamName, !IO),
+        string.format("%s:%03d: %s\n", [s(StreamName), i(LineNum),
+            s(Message)], FullMessage),
+        io.write_string(FullMessage, !IO),
+        io.set_exit_status(1, !IO)
+    ).

  %-----------------------------------------------------------------------------%

@@ -103,13 +114,13 @@
  :- mode expand_term(in, in, out, out) is det.

  expand_term(Term0, VarSet0, Term, VarSet) :-
-	( term_expansion(Term0, VarSet0, Term1, VarSet1) ->
-		Term = Term1,
-		VarSet = VarSet1
-	;
-		Term = Term0,
-		VarSet = VarSet0
-	).
+    ( term_expansion(Term0, VarSet0, Term1, VarSet1) ->
+        Term = Term1,
+        VarSet = VarSet1
+    ;
+        Term = Term0,
+        VarSet = VarSet0
+    ).

  %-----------------------------------------------------------------------------%

@@ -121,7 +132,9 @@
  :- mode term_expansion(in, in, out, out) is semidet.

  term_expansion(Term0, VarSet, Term, VarSet) :-
-	Term0 = term.functor(term.atom("<=>"), [A, B], Context),
-	Term = term.functor(term.atom(":-"), [A, B], Context).
+    Term0 = term.functor(term.atom("<=>"), [A, B], Context),
+    Term = term.functor(term.atom(":-"), [A, B], Context).

  %-----------------------------------------------------------------------------%
+:- end_module expand_terms.
+%-----------------------------------------------------------------------------%
Index: interpreter.m
===================================================================
RCS file: /home/mercury/mercury1/repository/mercury/samples/interpreter.m,v
retrieving revision 1.9
diff -u -r1.9 interpreter.m
--- interpreter.m	1 Nov 2006 23:11:23 -0000	1.9
+++ interpreter.m	10 Jan 2011 02:27:22 -0000
@@ -29,7 +29,6 @@
  :- pred main(io::di, io::uo) is det.

  %-----------------------------------------------------------------------------%
-%-----------------------------------------------------------------------------%

  :- implementation.

@@ -49,7 +48,7 @@
      (
          Args = [],
          io.stderr_stream(StdErr, !IO),
-        io.write_string(StdErr, "Usage: interpreter filename ...\n", !IO),
+        io.write_string(StdErr, "Usage: interpreter <filename> ...\n", !IO),
          io.set_exit_status(1, !IO)
      ;
          Args = [_ | _],
@@ -87,9 +86,11 @@
  :- pred write_solutions(list(varset)::in, term::in, io::di, io::uo) is det.

  write_solutions(Solutions, Goal, !IO) :-
-    ( Solutions = [] ->
+    (
+        Solutions = [],
          io.write_string("No.\n", !IO)
      ;
+        Solutions = [_ | _],
          write_solutions_2(Solutions, Goal, !IO),
          io.write_string("Yes.\n", !IO)
      ).
@@ -119,13 +120,18 @@
      io.write_string(File, !IO),
      io.write_string("'...\n", !IO),
      io.see(File, Result, !IO),
-    ( Result = ok ->
+    (
+        Result = ok,
          consult_until_eof(!Database, !IO),
          io.seen(!IO)
      ;
+        Result = error(Error),
+        io.error_message(Error, ErrorMessage),
          io.write_string("Error opening file `", !IO),
          io.write_string(File, !IO),
-        io.write_string("' for input.\n", !IO)
+        io.write_string("' for input: ", !IO),
+        io.write_string(ErrorMessage, !IO),
+        io.nl(!IO)
      ).

  :- pred consult_until_eof(database::in, database::out, io::di, io::uo) is det.
@@ -202,8 +208,8 @@
  unify(term.variable(X, _), term.variable(Y, _), VarSet0, VarSet) :-
      ( varset.search_var(VarSet0, X, BindingOfX) ->
          ( varset.search_var(VarSet0, Y, BindingOfY) ->
-            % both X and Y already have bindings - just
-            % unify the terms they are bound to
+            % Both X and Y already have bindings - just
+            % unify the terms they are bound to.
              unify(BindingOfX, BindingOfY, VarSet0, VarSet)
          ;
              % Y is a variable which hasn't been bound yet
@@ -217,7 +223,7 @@
          )
      ;
          ( varset.search_var(VarSet0, Y, BindingOfY2) ->
-            % X is a variable which hasn't been bound yet
+            % X is a variable which hasn't been bound yet.
              apply_rec_substitution(BindingOfY2, VarSet0, SubstBindingOfY2),
              ( SubstBindingOfY2 = term.variable(X, _) ->
                  VarSet = VarSet0
@@ -226,8 +232,8 @@
                  varset.bind_var(VarSet0, X, SubstBindingOfY2, VarSet)
              )
          ;
-            % both X and Y are unbound variables -
-            % bind one to the other
+            % Both X and Y are unbound variables -
+            % bind one to the other.
              ( X = Y ->
                  VarSet = VarSet0
              ;
@@ -266,10 +272,10 @@

  %-----------------------------------------------------------------------------%

-    % occurs(Term, Var, Subst) succeeds if Term contains Var,
-    % perhaps indirectly via the substitution.  (The variable must
-    % not be mapped by the substitution.)
-
+    % occurs(Term, Var, Subst) succeeds if Term contains Var, perhaps
+    % indirectly via the substitution.
+    % (The variable must not be mapped by the substitution.)
+    %
  :- pred occurs(term::in, var::in, varset::in) is semidet.

  occurs(term.variable(X, _), Y, VarSet) :-
@@ -293,16 +299,15 @@

  %-----------------------------------------------------------------------------%

-%   apply_rec_substitution(Term0, VarSet, Term) :
-%       recursively apply substitution to Term0 until
-%       no more substitions can be applied, and then
-%       return the result in Term.
-
+    % apply_rec_substitution(Term0, VarSet, Term):
+    % Recursively apply substitution to Term0 until no more substitutions can be
+    % applied, and then return the result in Term.
+    %
  :- pred apply_rec_substitution(term::in, varset::in, term::out) is det.

  apply_rec_substitution(V @ term.variable(Var, _), VarSet, Term) :-
      ( varset.search_var(VarSet, Var, Replacement) ->
-        % Recursively apply the substition to the replacement.
+        % Recursively apply the substitution to the replacement.
          apply_rec_substitution(Replacement, VarSet, Term)
      ;
          Term = V
@@ -327,12 +332,13 @@
  % and subindex on the name/arity of the first argument.)

  :- type database == list(clause).
-:- type clause --->
-    clause(
-        clause_vars :: varset,
-        clause_head :: term,
-        clause_body :: term
-    ).
+
+:- type clause
+    --->    clause(
+                clause_vars :: varset,
+                clause_head :: term,
+                clause_body :: term
+            ).

  :- pred database_init(database::out) is det.

@@ -360,3 +366,5 @@
      Clause = clause(VarSet, Head, Body).

  %-----------------------------------------------------------------------------%
+:- end_module interpreter.
+%-----------------------------------------------------------------------------%
Index: sort.m
===================================================================
RCS file: /home/mercury/mercury1/repository/mercury/samples/sort.m,v
retrieving revision 1.7
diff -u -r1.7 sort.m
--- sort.m	28 Jun 2006 09:11:07 -0000	1.7
+++ sort.m	10 Jan 2011 02:27:22 -0000
@@ -1,4 +1,6 @@
  %-----------------------------------------------------------------------------%
+% vim: ft=mercury ts=4 sw=4 et
+%-----------------------------------------------------------------------------%
  %
  % A simple sorting program.
  %
@@ -32,92 +34,100 @@
  %-----------------------------------------------------------------------------%

  main(!IO) :-
-	io.command_line_arguments(Args, !IO),
-	(
-		Args = [],
-		handle_args(no, no, !IO),
-		sort(!IO)
-	;
-		Args = [Input],
-		handle_args(yes(Input), no, !IO),
-		sort(!IO)
-	;
-		Args = [Input, Output], 
-		handle_args(yes(Input), yes(Output), !IO),
-		sort(!IO)
-	;
-		Args = [_, _, _ | _],
-		io.write_string("Usage: sort [Input [Output]]\\n", !IO)
-	).
+    io.command_line_arguments(Args, !IO),
+    (
+        Args = [],
+        handle_args(no, no, !IO),
+        sort(!IO)
+    ;
+        Args = [Input],
+        handle_args(yes(Input), no, !IO),
+        sort(!IO)
+    ;
+        Args = [Input, Output], 
+        handle_args(yes(Input), yes(Output), !IO),
+        sort(!IO)
+    ;
+        Args = [_, _, _ | _],
+        io.write_string("Usage: sort [Input [Output]]\\n", !IO)
+    ).

  :- pred handle_args(maybe(string)::in, maybe(string)::in, io::di, io::uo)
-	is det.
+    is det.

  handle_args(InArg, OutArg, !IO) :-
-	(
-		InArg = yes(InFilename),
-		io.see(InFilename, InResult, !IO),
-		(
-			InResult = ok
-		;
-			InResult = error(InError),
-			io.error_message(InError, InMsg),
-			error(InMsg)
-		)
-	;
-		InArg = no
-	),
-	(
-		OutArg = yes(OutFilename),
-		io.tell(OutFilename, OutResult, !IO),
-		(
-			OutResult = ok
-		;
-			OutResult = error(OutError),
-			io.error_message(OutError, OutMsg), 
-			error(OutMsg)
-		)
-	;
-		OutArg = no
-	).
+    (
+        InArg = yes(InFilename),
+        io.see(InFilename, InResult, !IO),
+        (
+            InResult = ok
+        ;
+            InResult = error(InError),
+            io.error_message(InError, InMsg),
+            error(InMsg)
+        )
+    ;
+        InArg = no
+    ),
+    (
+        OutArg = yes(OutFilename),
+        io.tell(OutFilename, OutResult, !IO),
+        (
+            OutResult = ok
+        ;
+            OutResult = error(OutError),
+            io.error_message(OutError, OutMsg), 
+            error(OutMsg)
+        )
+    ;
+        OutArg = no
+    ).

  :- pred sort(io::di, io::uo) is det.

  sort(!IO) :-
-	sort_2([], !IO).
+    sort_2([], !IO).

  :- pred sort_2(list(string)::in, io::di, io::uo) is det.

  sort_2(Lines0, !IO) :-
-	io.read_line_as_string(Result, !IO),
-	(
-		Result = error(Error),
-		io.error_message(Error, Msg),
-		error(Msg)
-	;
-		Result = eof,
-		output_sorted_lines(Lines0, !IO)
-	;
-		Result = ok(Line),
-		insert(Lines0, Line, Lines1),
-		sort_2(Lines1, !IO)
-	).
+    io.read_line_as_string(Result, !IO),
+    (
+        Result = error(Error),
+        io.error_message(Error, Msg),
+        error(Msg)
+    ;
+        Result = eof,
+        output_sorted_lines(Lines0, !IO)
+    ;
+        Result = ok(Line),
+        insert(Lines0, Line, Lines1),
+        sort_2(Lines1, !IO)
+    ).

  :- pred insert(list(T)::in, T::in, list(T)::out) is det.

  insert([], I, [I]).
  insert([H | T], I, L) :-
-	compare(R, I, H),
-	( R = (<) ->
-		L = [I, H | T]
-	;
-		insert(T, I, NT),
-		L = [H | NT]
-	).
+    compare(R, I, H),
+    (
+        R = (<),
+        L = [I, H | T]
+    ;
+        ( R = (=)
+        ; R = (>)
+        ),
+        insert(T, I, NT),
+        L = [H | NT]
+    ).

  :- pred output_sorted_lines(list(string)::in, io::di, io::uo) is det.

  output_sorted_lines([], !IO).
  output_sorted_lines([Line | Lines], !IO) :-
-	io.write_string(Line, !IO),
-	output_sorted_lines(Lines, !IO).
+    io.write_string(Line, !IO),
+    output_sorted_lines(Lines, !IO).
+
+%-----------------------------------------------------------------------------%
+:- end_module sort.
+%-----------------------------------------------------------------------------%
Index: ultra_sub.m
===================================================================
RCS file: /home/mercury/mercury1/repository/mercury/samples/ultra_sub.m,v
retrieving revision 1.8
diff -u -r1.8 ultra_sub.m
--- ultra_sub.m	21 Mar 2006 00:50:58 -0000	1.8
+++ ultra_sub.m	10 Jan 2011 02:27:22 -0000
@@ -1,4 +1,6 @@
-%------------------------------------------------------------------------------%
+%-----------------------------------------------------------------------------%
+% vim: ft=mercury ts=4 sw=4 et
+%-----------------------------------------------------------------------------%
  %
  % file: ultra_sub.m
  % author: conway.
@@ -14,7 +16,7 @@
  %
  % Variables in the pattern and template are represented by capital letters
  % (unfortunately limiting the number of variables to 26 ). Real capital letters
-% should be preceeded by a \.
+% should be preceded by a \.
  % Variables in the template that do not occur in the pattern are treated as
  % real capital letters.
  %
@@ -24,9 +26,10 @@
  % 7baz8bar9foo
  %
  % Strings that do not match the pattern are ignored.
+%
  %------------------------------------------------------------------------------%
-:- module ultra_sub.

+:- module ultra_sub.
  :- interface.

  :- import_module io.
@@ -38,106 +41,112 @@

  :- implementation.

-:- import_module list, string, char, map, svmap.
+
+:- import_module char.
+:- import_module list.
+:- import_module map.
+:- import_module string.
+:- import_module svmap.
+
+%------------------------------------------------------------------------------%

  main(!IO) :-
-	% I really should add some options for switching whether
-	% capitals or backslashed things are variables.
-	io.command_line_arguments(Args, !IO),
-	(
-		Args = [Pattern0, Template0 | Rest]
-	->
-		string.to_char_list(Pattern0, Pattern),
-		string.to_char_list(Template0, Template),
-		process_args(Rest, Pattern, Template, !IO)
-	;
-		io.write_string(
-			"usage: ultra_sub template pattern [strings]\n", !IO)
-	).
+    % I really should add some options for switching whether
+    % capitals or backslashed things are variables.
+    io.command_line_arguments(Args, !IO),
+    (
+        Args = [Pattern0, Template0 | Rest]
+    ->
+        string.to_char_list(Pattern0, Pattern),
+        string.to_char_list(Template0, Template),
+        process_args(Rest, Pattern, Template, !IO)
+    ;
+        io.write_string(
+            "usage: ultra_sub template pattern [strings]\n", !IO)
+    ).

  %------------------------------------------------------------------------------%

  :- pred process_args(list(string)::in, list(char)::in, list(char)::in,
-	io::di, io::uo) is det.
+    io::di, io::uo) is det.

  process_args([], _Pattern, _Template, !IO).
  process_args([Str | Strs], Pattern, Template, !IO) :-
-	(
-		string.to_char_list(Str, Chars),
-		map.init(Match0),
-		match(Pattern, Chars, Match0, Match)
-	->
-			% If the string matches, then apply the substitution
-		sub(Template, Match, ResultChars),
-		string.from_char_list(ResultChars, Result),
-		io.write_string(Result, !IO),
-		io.write_string("\n", !IO)
-	;
-		true
-	),
-	process_args(Strs, Pattern, Template, !IO).
+    (
+        string.to_char_list(Str, Chars),
+        map.init(Match0),
+        match(Pattern, Chars, Match0, Match)
+    ->
+        % If the string matches, then apply the substitution.
+        sub(Template, Match, ResultChars),
+        string.from_char_list(ResultChars, Result),
+        io.write_string(Result, !IO),
+        io.write_string("\n", !IO)
+    ;
+        true
+    ),
+    process_args(Strs, Pattern, Template, !IO).

  %------------------------------------------------------------------------------%

  :- pred match(list(char)::in, list(char)::in, map(char, list(char))::in, 
-	map(char, list(char))::out) is semidet.
+    map(char, list(char))::out) is semidet.

  match([], [], Match, Match).
  match([T | Ts], Chars, !Match) :-
-	(
-		char.is_upper(T)
-	->
-			% Match against a variable.
-		match_2(T, Chars, [], Ts, !Match)
-	;
-		T = ('\\') % don't you love ISO compliant syntax :-(
-	->
-		Ts = [T1 | Ts1],
-		Chars = [T1 | Chars1],
-		match(Ts1, Chars1, !Match)
-	;
-		Chars = [T | Chars1],
-		match(Ts, Chars1, !Match)
-	).
+    (
+        char.is_upper(T)
+    ->
+        % Match against a variable.
+        match_2(T, Chars, [], Ts, !Match)
+    ;
+        T = ('\\') % don't you love ISO compliant syntax :-(
+    ->
+        Ts = [T1 | Ts1],
+        Chars = [T1 | Chars1],
+        match(Ts1, Chars1, !Match)
+    ;
+        Chars = [T | Chars1],
+        match(Ts, Chars1, !Match)
+    ).

  :- pred match_2(char::in, list(char)::in, list(char)::in, list(char)::in, 
-	map(char, list(char))::in, map(char, list(char))::out) is semidet.
+    map(char, list(char))::in, map(char, list(char))::out) is semidet.

  match_2(X, Chars, Tail, Ts, !Match) :-
-	(
-			% Have we bound X? Does it match
-			% an earlier binding?
-		map.search(!.Match, X, Chars)
-	->
-		true
-	;
-		svmap.set(X, Chars, !Match)
-	),
-	(
-			% Try and match the remainder of the pattern
-		match(Ts, Tail, !Match)
-	->
-		true
-	;
-			% If the match failed, then try
-			% binding less of the string to X.
-		remove_last(Chars, Chars1, C),
-		match_2(X, Chars1, [C | Tail], Ts, !Match)
-	).
+    (
+        % Have we bound X? Does it match
+        % an earlier binding?
+        map.search(!.Match, X, Chars)
+    ->
+        true
+    ;
+        svmap.set(X, Chars, !Match)
+    ),
+    (
+        % Try and match the remainder of the pattern.
+        match(Ts, Tail, !Match)
+    ->
+        true
+    ;
+        % If the match failed, then try binding less of the string to X.
+        remove_last(Chars, Chars1, C),
+        match_2(X, Chars1, [C | Tail], Ts, !Match)
+    ).

  %------------------------------------------------------------------------------%

  :- pred remove_last(list(char)::in, list(char)::out, char::out) is semidet.

  remove_last([X | Xs], Ys, Z) :-
-	remove_last_2(X, Xs, Ys, Z).
+    remove_last_2(X, Xs, Ys, Z).

  :- pred remove_last_2(char::in, list(char)::in, list(char)::out, char::out)
-	is det.
+    is det.

  remove_last_2(X, [], [], X).
  remove_last_2(X, [Y | Ys], [X | Zs], W) :-
-	remove_last_2(Y, Ys, Zs, W).
+    remove_last_2(Y, Ys, Zs, W).

  %------------------------------------------------------------------------------%

@@ -145,28 +154,29 @@

  sub([], _Match, []).
  sub([C | Cs], Match, Result) :-
-	(
-		char.is_upper(C),
-		map.search(Match, C, Chars)
-	->
-		sub(Cs, Match, Result0),
-		list.append(Chars, Result0, Result)
-	;
-		C = ('\\')
-	->
-		(
-			Cs = [C1 | Cs1]
-		->
-			sub(Cs1, Match, Result0),
-			Result = [C1 | Result0]
-		;
-			sub(Cs, Match, Result0),
-			Result = Result0
-		)
-	;
-		sub(Cs, Match, Result0),
-		Result = [C | Result0]
-	).
+    (
+        char.is_upper(C),
+        map.search(Match, C, Chars)
+    ->
+        sub(Cs, Match, Result0),
+        list.append(Chars, Result0, Result)
+    ;
+        C = ('\\')
+    ->
+        (
+            Cs = [C1 | Cs1]
+        ->
+            sub(Cs1, Match, Result0),
+            Result = [C1 | Result0]
+        ;
+            sub(Cs, Match, Result0),
+            Result = Result0
+        )
+    ;
+        sub(Cs, Match, Result0),
+        Result = [C | Result0]
+    ).

  %------------------------------------------------------------------------------%
+:- end_module ultra_sub.
  %------------------------------------------------------------------------------%

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



More information about the reviews mailing list