Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Usage of &allow-other-keys in common lisp

Tags:

common-lisp

I want to make the most generic function and decided to go with keys as arguments. I want to use allow-other-keys since I want to use the function with any key.

Let me show you:

(defun myfunc (a &rest rest &key b &allow-other-keys)
  ;; Print A
  (format t "A = ~a~%" a)

  ;; Print B if defined
  (when b
    (format t "B = ~a~%" b))

  ;; Here ... I want to print C or D or any other keys
  ;; ?? 
)

(myfunc "Value of A")
(myfunc "Value of A" :b "Value of B")
(myfunc "Value of A" :b "Value of B" :c "Value of C" :d "Value of D")

I know that restis the remaining args but it has an array. It does not bind values c or d or even build them like an associative list (i.e to do sth like (cdr (assoc 'c rest)))

Do you have a clue or a solution ? Or maybe I am going in the wrong direction ?

Thanks in advance

like image 929
SmartyLisp Avatar asked Nov 25 '15 13:11

SmartyLisp


People also ask

How do we use a semicolon?

Use a semicolon to join two related independent clauses in place of a comma and a coordinating conjunction (and, but, or, nor, for, so, yet). Make sure when you use the semicolon that the connection between the two independent clauses is clear without the coordinating conjunction.

What is the difference between semicolon and colon?

Colons introduce or define something. The primary use of semicolons is to join two main clauses. The difference between semicolons and colons is that colons can combine two independent clauses, but their primary use is to join independent clauses with a list or a noun.

How do you use a colon in punctuation?

A colon is used to give emphasis, present dialogue, introduce lists or text, and clarify composition titles. Emphasis—Capitalize the first word after the colon only if it is a proper noun or the start of a complete sentence. (She had one love: Western Michigan University.)


1 Answers

Since when is &REST an array? The standard says list. In the case of keyword arguments, this is a property list. See getf to access elements of a property list.

One can also use DESTRUCTURING-BIND to access the contents of that property list:

CL-USER 15 > (defun foo (a &rest args &key b &allow-other-keys)
               (destructuring-bind (&key (c nil c-p) ; var default present?
                                         (d t   d-p)
                                         (e 42  e-p)
                                    &allow-other-keys)
                   args
                 (list (list :c c c-p)
                       (list :d d d-p)
                       (list :e e e-p))))
FOO

; c-p, d-p, e-p  show whether the argument was actually present
; otherwise the default value will be used

CL-USER 16 > (foo 10 :b 20 :d 30)
((:C NIL NIL) (:D 30 T) (:E 42 NIL))

But the same could have been done in the argument list already...

like image 157
Rainer Joswig Avatar answered Jan 02 '23 23:01

Rainer Joswig