Re: Closures versus objects

Robbert Haarman <[email protected]>
Newsgroups gmane.comp.lang.lightweight
Message-ID <[email protected]>
On Sat, Feb 17, 2007 at 06:58:46PM +0100, Pascal Costanza wrote:
> 
> It's a pity that there is not enough material "out there" that  
> explains generic functions in simple terms.

It's not that difficult, is it? Logically, a generic function is a 
function that looks at the types of its arguments, and choses a method 
to call based on them. CLOS adds a lot of other features, but the basic 
principle is that the most specific method is chosen, where earlier 
arguments trump later arguments, and subtypes trump supertypes.

To give an example, suppose one creates a generic function:

(defgeneric add (x y))

This means the function add expects two arguments.

Now, methods can be added:

(defmethod add ((x number) (y number)) (+ x y))

(defmethod add ((x string) (y string))
	(concatenate 'string x y))

(defmethod add ((x integer) (y integer)) (* x y))

...and when we call add, different actions will be taken, depending on 
the types of the arguments:

(add 1/3 1/4) => 7/12
(add "foo" "bar") => "foobar"
(add 1 2) => 2
(add 1 1/3) => 4/3
(add 'foo 'bar) => error: no applicable method

Regards,

Bob

-- 
In a democracy, people get the government they deserve.
signature.asc (application/pgp-signature, 189 B)
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.6 (GNU/Linux)

iD8DBQFF12Pgfb9wcmD+WN4RAi2FAKCgaibPkkCt2Z5OvNjR9dEAmcpCvwCgktYN
MIfj8IeBJd4/1R6Aj8zGOss=
=I2E1
-----END PGP SIGNATURE-----
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.