[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: 'length' function for lists and cons cells?
From: |
Thorsten Jolitz |
Subject: |
Re: 'length' function for lists and cons cells? |
Date: |
Thu, 21 Mar 2013 23:09:01 +0100 |
User-agent: |
Gnus/5.130002 (Ma Gnus v0.2) Emacs/24.2 (gnu/linux) |
"Drew Adams" <drew.adams@oracle.com> writes:
>> 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.
I probably wasn't entirely clear to me either ..
> 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))))))
>
But with this function you answered the question I really wanted to ask:
how to distinguish between a true list and a cons cell - by the use of
'atom' on the last cdr. Maybe pretty basic, but I haven't done it
before.
> (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))
Thanks, nice solution - very useful.
--
cheers,
Thorsten
- Re: 'length' function for lists and cons cells?, Pascal J. Bourguignon, 2013/03/21
- Re: 'length' function for lists and cons cells?, Thorsten Jolitz, 2013/03/21
- Re: 'length' function for lists and cons cells?, Mark Skilbeck, 2013/03/22
- Re: 'length' function for lists and cons cells?, Thorsten Jolitz, 2013/03/22
- Message not available
- Re: 'length' function for lists and cons cells?, Pascal J. Bourguignon, 2013/03/23
- RE: 'length' function for lists and cons cells?, Drew Adams, 2013/03/23
- Message not available
- Re: 'length' function for lists and cons cells?, Pascal J. Bourguignon, 2013/03/23
- RE: 'length' function for lists and cons cells?, Drew Adams, 2013/03/24