< Back to IRCAM Forum

Om::defmethod! against defun

Hi all,

in many of the om libraries the om::defmethod! is strongly present.
What is the difference between om::defmethod! and defun? (except the obvious one that the (om::defmethod!) is part of the om package…)
Is the one more advisable than the other to be used for an om library?

Thank you in advance,

Dimitris

Dear Dimitris,

In short:

defun is to define a function
defmethod is to define a method.

Now what’s the difference between a function and a method in CLOS:

A function will apply an operation on its argument without taking into account the type of its argument.

A method, on the contrary will apply an operation on its argument depending on the type of its argument.

Example:

the function + applies addition on the elements of its argument and here the arguments are simple numbers (integers float ratio etc.) BUT not lists!

om+ method (there are four of them) applies:

om+ number number
om+ list number
om+ number list
om+ list list

Meaning om+ is “intelligent” and has a method for each type combination of its arguments.

I hope this short anf fast explanation is helpfull

See here for functions:
https://lisp-lang.org/learn/functions

here for methods:
https://lisp-lang.org/learn/clos

Best
K

Thank you a lot Karim!

Greetings,

Dimitris

In this sense this example of code:
(defun rationalize-float (lst)
“Convert floats into ratios”
(mapcar (lambda (x)
(rationalize (/ x 4)))
lst))

would be better in this way if included in a library:

(defun ratfloat (lst)
(mapcar (lambda (x)
(rationalize (/ x 4)))
lst))

(om::defmethod! rationalize-float (lst)
“Convert floats into ratios”
:initvals ‘(1.0 0.625 3.0 0.109375 0.25)
:indoc ‘(“list”)
:icon 01
(ratfloat lst))

I know this example does not need so much intelligent selection of different kind of inputs but is it in principle correct as code?

thank you!

Dimitris

To be more precise:


;for atom
(om::defmethod! rationalize-float ((lst number))
  (rationalize lst))

;(rationalize-float 1.9)

;for list
(om::defmethod! rationalize-float ((lst list))
  “Convert floats into ratios”
  :initvals ‘(1.0 0.625 3.0 0.109375 0.25)
  :indoc ‘(“list”)
  :icon 01
  (mapcar (lambda (x)
            (rationalize (/ x 4)))
          lst))

;(rationalize-float  ‘(1.0 0.625 3.0 0.109375 0.25))

You will observe the argument (lst number) , for simple element and (lst list) for a list.

Best
K

Great!
Thank you Karim!
Dimitris