list length

From: Algernon (algernon_at_dmv.com)
Date: 07/05/04

  • Next message: vannoord_at_let.rug.nl: "Re: list length"
    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


  • Next message: vannoord_at_let.rug.nl: "Re: list length"

    Relevant Pages

    • Re: NGM and species sightings
      ... People on the Plains got the T-shirt, and the joke, ... Much I wouldn't call "art" either, ... and fooling ourselves. ... Penguins became jokes because of people in tuxes. ...
      (rec.backcountry)
    • Re: Fire/smooke detection in the shop
      ... State of the art stuff ... No fooling it with dust. ... Should only cost you about $15K. ...
      (rec.woodworking)