[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: Chained Object Type Predicates
From: |
Pascal J. Bourguignon |
Subject: |
Re: Chained Object Type Predicates |
Date: |
Mon, 08 Jun 2009 14:58:08 +0200 |
User-agent: |
Gnus/5.101 (Gnus v5.10.10) Emacs/22.2 (gnu/linux) |
Nordlöw <per.nordlow@gmail.com> writes:
> How should i implement chained type predicate functions, for example
>
> (defun list-of-numbers-p (object) (and (listp object) ...))
>
> should return t if object is of type list (listp) and its elements in
> turn all are of type string (stringp) otherwise nil.
Then why don't you call it list-of-strings-p ?
There are several ways to do so.
One way is to notice that a list is either nil (meaning the empty list)
or made of a first item followed by a rest sublist.
So you could write:
(defun list-of-numbers-p (object)
(or (null object)
(and (consp object)
(numberp (first object))
(list-of-numbersp (rest object)))))
Another would be to use reduce:
(require 'cl)
(defun list-of-numbers-p (object)
(and (listp object)
(reduce (lambda (&optional (r rp) e)
(if rp (and r (numberp e)) t)) object)))
Finally, you may notice that in a list of numbers, every element is a number:
(require 'cl)
(defun list-of-numbers-p (object)
(and (listp object) (every (function numberp) object)))
You may write a macro to build these functions automatically:
(defun proper-list-p (object)
(labels ((step (slow fast)
(cond ((eq slow fast) nil) ; circular list
((null (cdr fast)) t)
((atom (cdr fast)) nil) ; dotted list
((null (cdr (cdr fast))) t)
((atom (cdr (cdr fast))) nil) ; dotted list
(t (step (cdr slow) (cdr (cdr fast)))))))
(cond
((null object) t) ; empty list
((atom object) nil) ; not a list
((null (cdr object)) t) ; one-element list
(t (step object (cdr object))))))
(defmacro proper-list-of (predicate)
`(lambda (object)
(and (proper-list-p object)
(every (function ,predicate) object))))
(funcall (proper-list-of integerp) '(1 2 3 4)) --> t
(funcall (proper-list-of integerp) '(1 2 "3" 4)) --> nil
(funcall (proper-list-of integerp) '(1 2 3 . 4)) --> nil
(funcall (proper-list-of integerp) '(1 2 #1=(3 4 . #1#))) --> nil
--
__Pascal Bourguignon__