help-gnu-emacs
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: 'length' function for lists and cons cells?


From: duthen . cnv
Subject: Re: 'length' function for lists and cons cells?
Date: Mon, 25 Mar 2013 08:24:05 -0700 (PDT)
User-agent: G2/1.0

Le jeudi 21 mars 2013 21:10:10 UTC+1, Drew Adams a écrit :
> > which function could I use when I map an alist e.g. with dolist,
> > that contains both types of associations as shown below: cons 
> > cells, or lists with 3 or more elements?
> > 'length' doesn't work on cons cells:
> 
> > Debugger entered--Lisp error: (wrong-type-argument listp "c")
> >   length(("a" . "c"))
> 
> It's not clear to me what you're asking.
> 
> Are you looking for a "length" function that works for both true lists
> (but why do you mention 3 or more elements?) and a cons whose last cdr
> is a non-nil atom?
> 
> If so then it is up to you to define what you want such a "length" to be/mean.
> 
> Perhaps what you want is something like this?
> 
> (defun thorsten-len (xs)
>   (cond ((null xs)       0)
>         ((null (cdr xs)) 1)
>         ((atom (cdr xs)) 2)
>         (t (1+ (thorsten-len (cdr xs))))))
> 
> (thorsten-len '(1 2 3 4 . 5)) => 5
> 
> (setq foo  '((a . 1) (b 2) (c (3 3 3)) (d 4 4 4 . 4)))
> (mapcar #'thorsten-len foo) => (2 2 2 5)
> 
> (setq bar  ())
> (dolist (ff  foo) (push ff bar))
> (reverse bar) => ((a . 1) (b 2) (c  (3 3 3)) (d 4 4 4 . 4))

Considering that:
 (a b)     contains 2 cons cells and 2 values (a and b),
 (a b . c) contains 2 cons cells and 3 values (a b and c),
 (a b c)   contains 3 cons cells and 3 values (a b and c).

So, one possible point of vue (not necessarily mine, though!) 
could consider that (a b . c) is "a little bit longer" than (a b) 
and "a little bit shorter" than (a b c)!

Hence, the function:
(defun semi-length (xs)
  (cond ((null xs)  0)
        ((atom xs)  .5)
        (t (1+ (semi-length (cdr xs))))))

(mapcar (lambda (x) (cons (semi-length x) x))
       '(()
         a
         (a)
         (a . b)
         (a b)
         (a b . c)
         (a b c)))

((0) (0.5 . a) (1 a) (1.5 a . b) (2 a b) (2.5 a b . c) (3 a b c))

A true list is just one whith an integer semi-length
whereas a dotted-paired list is one with a fractional semi-length ! :)



reply via email to

[Prev in Thread] Current Thread [Next in Thread]