[m-users.] if/then/else griping.
Peter Wang
novalazy at gmail.com
Mon Jul 22 20:35:58 AEST 2019
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.
> *Syntax* issues with languages, I'd normally disregard as trivial,
> but I don't think *formatting* is trivial. Formatting is so
> important that
>
> 1. languages like Python, Haskell, Nim, make it meaningful.
>
> 2. languages like Go (gofmt), Ada (gnatpp), Elm, make it
> automatic. You don't format your code; a code prettifier does.
An automatic formatter would be nice for Mercury as well.
> Maybe this is untrue, but my assumption for a while was that
> if/then/else was added to Mercury in the first place because people
> learning Mercury complained about formatting problems with the
> Prolog-style conditionals.
You can see from the changelog that the keywords were already available
very early on due to the NU-Prolog influence (NU-Prolog was used to
bootstrap Mercury). As for why NU-Prolog had the keywords, someone will
probably tell us.
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.
> Well, having said all that, I've already realized that the
> unbalanced-if is what the stdlib is going with, so I'll try that and
> see if it eventually stops bothering me.
>
> I do think that the tutorial should reflect this style if that's
> what's recommended. Right now the tutorial has
>
> fib(N, X) :-
> ( if N =< 2
> then X = 1
> else fib(N - 1, A), fib(N - 2, B), X = A + B
> ).
The formatting in the tutorial is just the original author's preference.
We should probably change it.
Peter
More information about the users
mailing list