[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 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).

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

--
Jeff Brown | Jeffrey Benjamin Brown