Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redundancy in Lisp

I have started to learn Lisp and was wondering if all the redundancies of doing a particular task in several different ways useful? Am sure experienced Lisp programmers can answer this question.

To just quote an example. We can create functions by following 2 different ways.

(defun add2 (x) (+ x 2))

or

(setf (symbol-function 'add2)
  #'(lambda (x) (+ x 2))

I understand that this provides flexibility to achieve different things. But a proper explanation as to why have all this redundancy can help me understand things better.

like image 522
roshang Avatar asked Dec 02 '22 00:12

roshang


2 Answers

The first form exists because defining functions is such a common chore that you want a convenient syntax for it.

The second form exists because sometimes, you want to do advanced things with macros generating function definitions and whatnot.

If there had been no defun, we could still define functions with your second form, but nobody would be programming in Lisp because a simple task would be extremely arduous. Every programmer would be designing their own defun macro, incompatible with all the others.

like image 111
Fred Foo Avatar answered Dec 19 '22 02:12

Fred Foo


If you look at DEFUN in existing implementations, it does much more than just defining a function. It records for example the definition location for the IDE (development environment), sets the documentation, records the type information, ...

Often Lisp exposes a machinery in terms of a functional interface. The typical usage is then done via a set of macros which provide a convenient interface and side effects in the development environment.

Sometimes, with CLOS, there is even an object-oriented implementation underneath the functional interface.

The picture then looks like this

macros <- used by the programmer, convenient to use
   ^
   |
functions <- user interface to the implementation
   ^
   |
CLOS (classes, instances, generic functions) <- low-level extensible machine
like image 27
Rainer Joswig Avatar answered Dec 19 '22 04:12

Rainer Joswig