[m-users.] Why does list.length use an auxiliary function?

Jeffrey Brown jeffbrown.the at gmail.com
Sun Dec 23 17:10:36 AEDT 2018


The length function from the list module[1] is a lot of code. This simple
definition seems sufficient:

    :- pred simple_length(list(_T), int).
    :- mode simple_length(in, out) is det.
    :- func simple_length(list(T)) = int.

    simple_length( [], 0 ).
    simple_length( [_|Rest], N ) :-
      simple_length( Rest, N0 ),
      N = 1 + N0.
    simple_length(List) = N :-
      simple_length(List, N).

Why is it instead this more complex one?

    :- pred length(list(_T), int).
    :- mode length(in, out) is det.
    :- func length(list(T)) = int.

    length(L, N) :-
        list.length_acc(L, 0, N).

    length(Xs) = N :-
        list.length(Xs, N).

    :- pred length_acc(list(T), int, int).
    :- mode length_acc(in, in, out) is det.

    length_acc([], N, N).
    length_acc([_ | L1], N0, N) :-
        N1 = N0 + 1,
        list.length_acc(L1, N1, N).

[1] https://github.com/Mercury-Language/mercury/blob/master/library/list.m


-- 
Jeff Brown | Jeffrey Benjamin Brown
Website <https://msu.edu/~brown202/>   |   Facebook
<https://www.facebook.com/mejeff.younotjeff>   |   LinkedIn
<https://www.linkedin.com/in/jeffreybenjaminbrown>(spammy, so I often miss
messages here)   |   Github <https://github.com/jeffreybenjaminbrown>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.mercurylang.org/archives/users/attachments/20181223/55330bc3/attachment.html>


More information about the users mailing list