list length
From: Algernon (algernon_at_dmv.com)
Date: 07/05/04
- Previous message: Zoltan Somogyi: "Re: Metainterpreter that prints call stack in case of failure."
- Next in thread: vannoord_at_let.rug.nl: "Re: list length"
- Reply: vannoord_at_let.rug.nl: "Re: list length"
- Reply: Algernon: "Re: list length"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Mon, 5 Jul 2004 05:04:42 -0400
I've been fooling around with writing a tutorial (mainly to improve my
skills) and I've used an example from Art of Prolog for finding the length
of a list namely:
length(List,N) :- nonvar(List), length1(List,N).
length(List,N) :- var(List), nonvar(N), length2(List,N).
length1([_|Ls],N) :-
length1(Ls,N1),
N is N1 + 1.
length1([],0).
length2([_|Ls],N) :-
N > 0,
N1 is N - 1,
length2(Ls,N1).
length2([],0).
using the meta-language predicates var/1 and nonvar/1 we are able to
determine the length of a list is N given the list or generate a list of
length N given N. As I was fooling with this example, I starting thinking of
accumulators so I came up with this:
list_length(List,N) :- list_length(List,0,N).
list_length([],N,N).
list_length([_L|Ls],N0,N) :-
N1 is N0 + 1,
list_length(Ls,N1,N).
I've tested this and found equivalent solutions for both versions of length
as well as the built-in length/2. My question is, have I missed something or
is it better to use list_length/2?
thanks
- Previous message: Zoltan Somogyi: "Re: Metainterpreter that prints call stack in case of failure."
- Next in thread: vannoord_at_let.rug.nl: "Re: list length"
- Reply: vannoord_at_let.rug.nl: "Re: list length"
- Reply: Algernon: "Re: list length"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|
|