Optional and keyword parameters in generic functions

Discussion of Common Lisp

Optional and keyword parameters in generic functions

Postby janders468 » Mon Dec 29, 2008 1:20 pm

Is it possible to specialize and give a default value for an optional parameter in a generic function, i.e:

(defgeneric foo (one &optional two))

(defmethod foo ((one number) &optional (two number))
(+ one two))

This is read as though the optional parameter has a default value of number instead of specializing on the type number. I may be missing something obvious but
any help or a pointer to where this has been discussed would be greatly appreciated.

Thanks!
janders468
 
Posts: 16
Joined: Fri Oct 17, 2008 12:27 pm

Re: Optional and keyword parameters in generic functions

Postby nuntius » Mon Dec 29, 2008 6:31 pm

You can not specialize the optional parameters in generic functions. It would horribly complicate the CLOS type dispatch algorithm and could only reasonably apply in the case of a tie on the main parameters.

Here's an extract from the CLHS page for defmethod. http://www.lispworks.com/documentation/HyperSpec/Body/m_defmet.htm
Code: Select all
specialized-lambda-list::= ({var | (var parameter-specializer-name)}*
                            [&optional {var | (var [initform [supplied-p-parameter] ])}*]
                            [&rest var]
                            [&key{var | ({var | (keywordvar)} [initform [supplied-p-parameter] ])}*
                                 [&allow-other-keys] ]
                            [&aux {var | (var [initform] )}*] )


Notice the difference in the lambda lists for a normal var versus those for &optional, &key, and &aux. Only the required variables can have specializers.

If you really need this secondary dispatch, how about defining another generic function?

Something like
Code: Select all
(defgeneric foo-helper (one two) "secondary dispatch for calls to FOO with two args")
(defmethod foo-helper ((one number) (two number))
  (+ one two))
(defmethod foo ((one number) &optional two)
  (foo-helper one two))
User avatar
nuntius
 
Posts: 500
Joined: Sat Aug 09, 2008 10:44 am
Location: Burlington, MA

Re: Optional and keyword parameters in generic functions

Postby janders468 » Mon Dec 29, 2008 7:12 pm

Thanks for straightening that out for me. I will just define another function but wanted to see if this was a possibility.
janders468
 
Posts: 16
Joined: Fri Oct 17, 2008 12:27 pm


Return to Common Lisp

Who is online

Users browsing this forum: No registered users and 2 guests