Some extensions of and and or in Lisp

I found a very clear explanation of and and or in this page: http://www.cs.cmu.edu/Groups/AI/html/cltl/clm/node75.html

(and form1 form2 ... ) evaluates each form, one at a time, from left to right.

If any form evaluates to nil, the value nil is immediately returned without evaluating the remaining forms.

If every form but the last evaluates to a non-nil value, and returns whatever the last form returns.

(or form1 form2 ... ) evaluates each form, one at a time, from left to right.

If any form other than the last evaluates to something other than nil, or immediately returns that non-nil value without evaluating the remaining forms.

If every form but the last evaluates to nil, or returns whatever evaluation of the last of the forms returns.

Here’s some extensions of and and or.

and-nth is similar to and but it returns the value of the n-th argument instead of the last one.


(defun and-nth (n &rest lst)
  (when (eval (cons 'and lst))
    (nth n lst)))

or-nth is similar to or but it returns the value of the n-th argument instead of the first non-nil argument.


(defun or-nth (n &rest lst)
  (when (eval (cons 'or lst))
    (nth n lst)))    

and-funcall and and-apply apply some function to the arguments if all of them are non-nil

    
(defun and-funcall (fn &rest lst)
  (when (eval (cons 'and lst))
    (funcall fn lst)))

(defun and-apply (fn &rest lst)
  (when (eval (cons 'and lst))
    (apply fn lst)))

For example:


(and-apply #'+ 1 2 3)

returns 6


(and-funcall #'butlast 1 2 3)

returns (1 2)


(and-apply #'+ 1 2 nil  3)

returns nil

or-funcall and or-apply apply some function to only those arguments that are non-nil


(defun or-funcall (fn &rest lst)
  (when (eval (cons 'or lst))
    (funcall fn (list-not-nill lst))))

(defun or-apply (fn &rest lst)
  (when (eval (cons 'or lst))
    (apply fn (list-not-nill lst))))

For example:


(or-apply #'+ 1 2 nil  3)

returns 6


(or-funcall #'butlast 1 2 nil  3)

returns (1 2)

The function list-not-nill used in both or-funcall and or-apply returns the list of all non-nil parameters:


(defun list-not-nill (lst)
  (loop for i in lst when (not (null i)) collect i))

For example:


(list-not-nill '(1 2 nil 3))

returns (1 2 3)

Advertisements
Published in: on 31/03/2014 at 21:24  Leave a Comment  

The URI to TrackBack this entry is: https://burubaxair.wordpress.com/2014/03/31/some-extensions-of-and-and-or-in-lisp/trackback/

RSS feed for comments on this post.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: