[m-users.] [Beginner] How to make a function using list pattern matching deterministic

Zoltan Somogyi zoltan.somogyi at runbox.com
Fri Oct 14 22:54:11 AEDT 2022



On Fri, 14 Oct 2022 16:29:41 +0530, Razetime <rraghu.11502 at gmail.com> wrote:
> Currently I have these two predicates in my program that I think I can
> make deterministic.
> 
> :- pred entry(list(string)::in, list(int)::out) is det.
> entry(Dirs, Out) :-
>   map((pred(X::in, [L,R]::out) is det :-
>          split(X, 1, L, R)),
>        Dirs, Spl),
>   foldl2((pred([T, B]::in, D::in, Ds::out, P::in, Ps::out) is det :-
>             rot(T, D, Ds),
>             BI = string.det_to_int(B),
>             map((pred(X::in, Y::out) is det :- Y = X*BI), Ds, Dso),
>             map_corresponding((pred(X::in, Y::in, Z::out) is det :- Z
> = X+Y), P, Dso, Ps)
>         ), Spl, [0, 1], _, [0, 0], Out).

This code nests lambda expressions three levels deep.
That is not a good idea even for expert Mercury programmers.
If you write each of those as a separate named predicate,
any error messages you get from the compiler will be
significantly more specific, and therefore more easily understandable.
 
> :- pred rot(string::in, list(int)::in, list(int)::out) is det.
> rot("L", [X, Y], [A, B]) :-
>   A = -Y,
>   B =  X.
> rot("R", [X, Y], [A, B]) :-
>   A =  Y,
>   B = -X.

Many people who come to Mercury (or Haskell, or other
languages with Hindley-Milner type systems) from untyped
languages such as Prolog or Lisp, often use lists as a universal
data structure. While lists are also important in Mercury,
they are used for ordered collections whose size is variable.
In situations like this where your lists are of a fixed size,
it is much better to define and use a type specific to this
purpose. In this case, I am guessing that something like

:- type coord
   --->   coord(coord_x: int, coord_y: int).

would be more suitable than a two element list.
And it would solve your determinism problem,
though not necessarily in the way you want
(since I don't know what you want this code to achieve).

Zoltan.



More information about the users mailing list