Tail Recursion

View: New views
2 Messages — Rating Filter:   Alert me  

Tail Recursion

by Frank Schwidom :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

Hi,

I want to create lists of N unbound elements. If I use the first variant:

mklist( 0, []) :- !.
mklist( N, L) :-
 N2 is N - 1,
 L=[ _| L2],
 mklist( N2, L2)
_______________________________________________
SWI-Prolog mailing list
SWI-Prolog@...
https://mailbox.iai.uni-bonn.de/mailman/listinfo.cgi/swi-prolog

Re: Tail Recursion

by Paulo Moura :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message


On 2009/10/11, at 12:59, Frank Schwidom wrote:

> I want to create lists of N unbound elements. If I use the first  
> variant:
>
> mklist( 0, []) :- !.
> mklist( N, L) :-
> N2 is N - 1,
> L=[ _| L2],
> mklist( N2, L2)


And your question is? Note that you can also use the SWI-Prolog built-
in predicate length/2 to construct your list. For example:

?- length(L, 7).
L = [_G278, _G281, _G284, _G287, _G290, _G293, _G296].

In other Prolog compilers, length/2, if not a built-in predicate, is  
usually available in a library. In my case, the Logtalk implementation  
of this library predicate when L is unbound uses the code:

        make_list(N, List):-
                ( N =:= 0 ->
                        List = []
                ; M is N-1,
                        List = [_| Tail],
                        make_list(M, Tail)
                ).

(N is guaranteed to be a non-negative integer when make_list/2 is  
called)

Cheers,

Paulo


-----------------------------------------------------------------
Paulo Jorge Lopes de Moura, PhD
Assistant Professor
Dep. of Computer Science, University of Beira Interior
6201-001 Covilhã, Portugal

Office 3.18  Ext. 3276
Phone: +351 275319891 Fax: +351 275319899
Email: <mailto:pmoura@...>

Home page: <http://www.di.ubi.pt/~pmoura>
Research:  <http://logtalk.org/> Blog: <http://blog.logtalk.org/>
-----------------------------------------------------------------

_______________________________________________
SWI-Prolog mailing list
SWI-Prolog@...
https://mailbox.iai.uni-bonn.de/mailman/listinfo.cgi/swi-prolog