Jump to content

defun

From Wikipedia, the free encyclopedia

This is an old revision of this page, as edited by WOSlinker (talk | contribs) at 08:40, 1 December 2020 (change source to syntaxhighlight). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

defun (short for "define function") is a macro in the Lisp family of programming languages that defines a function in the global environment[1] that uses the form:

(defun <function-name> (<parameter-1> <parameter-2> ... <parameter-N>) 
  "optional documentation"
  <function-body>...)

Defining the function addnumbers that adds two numbers:

 ;; Define a function that adds two numbers together:
 (defun addnumbers (number1 number2)
   (+ number1 number2))
 (addnumbers 5 4)
 9

Defining function square that squares a number:

 ;; Define a function that squares a number:
 (defun square (x) 
   (* x x))
 (square 4)
 16

Defining a function that returns the factorial of a number:

 (defun factorial (number)
   "calculates the factorial"
   (if (= number 1)
       1
       (* number (factorial (- number 1)))))
 (factorial 6)
 720

See also

References

  1. ^ "Macro DEFUN". LispWorks Ltd.