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: Thorsten Jolitz
Subject: Re: 'length' function for lists and cons cells?
Date: Fri, 22 Mar 2013 10:57:28 +0100
User-agent: Gnus/5.130002 (Ma Gnus v0.2) Emacs/24.2 (gnu/linux)

Mark Skilbeck <m@iammark.us> writes:

> It just doesn't make sense to talk about the length of a dotted
> _pair_, a cons-cell: it has a car and a cdr.

yes, but length is only an example, its about mapping an alist with true
lists and cons cells as elements, and in some situations it seems
necessary to make a program act differently depending on what the
element is that is processed. 

Here is another example:

1. cadr does the right thing

,------------------
| (cdr '("a" "1"))
| ("1")
| 
| (cadr '("a" "1"))
| "1"
`------------------

2. cdr does the right thing, cadr gives an error

,--------------------------------------------------------------
| (cdr '("a" . "1"))
| "1"
| 
| (cadr '("a" . "1"))
| 
| Debugger entered--Lisp error: (wrong-type-argument listp "1")
|   cadr(("a" . "1"))
`--------------------------------------------------------------

So if both, true lists and cons cells, are processed in a 'dolist' or
'mapc', how do you get that second string element without writing
something like 

,----------------------------------
| (defun tj/act-conditional (lst)
|    (if (cdr (last lst))
|       (cdr lst)
|      (cadr lst)))
| 
| (tj/act-conditional '("a" . "1"))
| "1"
| 
| (tj/act-conditional '("a" "1"))
| "1"
`----------------------------------

otherwise:

,--------------------------------------------------------------
| (defun tj/act-blindly-1 (lst) (cdr lst))
| (defun tj/act-blindly-2 (lst) (cadr lst))
| 
| (tj/act-blindly-1 '("a" . "1"))
| "1"
| 
| (tj/act-blindly-2 '("a" . "1"))
| 
| Debugger entered--Lisp error: (wrong-type-argument listp "1")
|   cadr(("a" . "1"))
| 
| 
| (tj/act-blindly-1 '("a" "1"))
| ("1")
| 
| (tj/act-blindly-2 '("a" "1"))
| "1"
`--------------------------------------------------------------


-- 
cheers,
Thorsten




reply via email to

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