[m-users.] if/then/else griping.

Julian Fondren jfondren at minimaltype.com
Mon Jul 22 21:13:56 AEST 2019


On 2019-07-22 05:35, Peter Wang wrote:
> Hi,
> 
> On Mon, 22 Jul 2019 01:15:57 -0500, Julian Fondren
> <jfondren at minimaltype.com> wrote:
>> 
>>    % Mercury stdlib seems to have settled on this style.
>>    % the initial 'if' looks unbalanced vs. the rest of the code.
>>    daytype(D) = R :-
>>        ( if D = wednesday then
>>            R = "humpday"
>>        else if (D = sunday; D = saturday) then
>>            R = "weekend"
>>        else
>>            R = "workday"
>>        ).
> 
> Note that you can omit the parens in the second condition when using 
> the
> if/then/else keywords. It's also usual to leave spaces either side of a
> semicolon to make it stand out more.

Oh, that's a nice benefit.

> 
> I used to prefer the -> ; syntax, and I still think "else if ... then"
> clutters up the condition. However, the if/then/else keywords do have
> the advantage that when you are in the middle of some huge predicate
> (it happens) you don't need to go scanning very far forwards or
> backwards to find the telltale "->" that lets you know you are looking
> at an if-then-else rather than a conjunction or disjunction.

I've already noticed that it looks a lot better in larger cases. f.e.

   main(!IO) :-
       io.command_line_arguments(Args, !IO),
       ( if
           Args = [DayString],
           Lowered = to_lower(DayString),
           Term = Lowered ++ ".",
           io.read_from_string("args", Term, length(Term),
               ok(Day), io.posn(0, 0, 0), _)
       then
           io.format("daytype(%s) = ""%s"".\n",
               [s(Lowered), s(daytype(Day))], !IO)
       else
           io.progname_base("daytype", Program, !IO),
           io.format(io.stderr_stream, "usage: %s <weekday>\n", 
[s(Program)], !IO),
           io.set_exit_status(1, !IO)
       ).

vs.

   main(!IO) :-
       io.command_line_arguments(Args, !IO),
       (
           Args = [DayString],
           Lowered = to_lower(DayString),
           Term = Lowered ++ ".",
           io.read_from_string("args", Term, length(Term),
               ok(Day), io.posn(0, 0, 0), _)
       ->
           io.format("daytype(%s) = ""%s"".\n",
               [s(Lowered), s(daytype(Day))], !IO)
       ;
           io.progname_base("daytype", Program, !IO),
           io.format(io.stderr_stream, "usage: %s <weekday>\n", 
[s(Program)], !IO),
           io.set_exit_status(1, !IO)
       ).



More information about the users mailing list