Path: utzoo!attcan!uunet!ginosko!xanth!ames!think!barmar From: barmar@think.COM (Barry Margolin) Newsgroups: comp.lang.lisp Subject: Re: optional and key arguments Message-ID: <28251@news.Think.COM> Date: 27 Aug 89 21:21:03 GMT References: <64922@linus.UUCP> Sender: news@Think.COM Distribution: comp.lang.lisp Organization: Thinking Machines Corporation, Cambridge MA, USA Lines: 61 In article <64922@linus.UUCP> bds@mbunix (Smith) writes: >(defun test (a b &optional (c 0) &key (d 1)) >(test 5 4 :d 0) results in an error. >Is this the Common Lisp standard? Yes. See p.61 of CLtL. Optional arguments are processed before keyword arguments. > If so, does it make sense? Yes. How would you propose that Lisp determine whether the :D is supposed to be an argument name or the value of the C argument? In the above case *you* can tell that it was intended as an argument name because you gave an incorrect number of arguments, but that isn't always possible. Consider: (defun test (&optional a b &key d) ...) (test :d :e) This binds A to :D, B to :E, and D to NIL and gets no error. How would a Lisp system determine that you actually meant to set the D argument? Don't try to special case arguments that are symbols in the KEYWORD package. First of all, that would break lots of things; many functions that keyword-valued arguments. Second, argument names don't even have to be in the KEYWORD package; consider: (defun test (&optional a b &key ((c-name c) nil)) ...) (test 'c-name 'c-val) This binds A to C-NAME, B to C-VAL, and C to NIL. Lisp can't tell that you meant it to be interpreted as (test nil nil 'c-name 'c-val) >In our case, we had 3 optional arguments, and we >wanted to use the default values, but to set the key argument to >something else. This is why it's generally a bad idea to have both optional and keyword arguments in the same function. You should turn them all into keyword arguments. >It seems a violation of the notion of optional >arguments to have to specify them. Well, you have to specify the Nth optional argument if you want to specify the N+1th one. Named arguments can be thought of as a single, last optional argument which is automatically parsed. Or they can be considered as automatically-parsed &REST arguments. Either of these analogies will help you remember that optional arguments must be specified first. Lisp isn't Ada. Barry Margolin Thinking Machines Corp. barmar@think.com {uunet,harvard}!think!barmar