Wednesday, July 15, 2009

Define Function (defun)

As an aside, "A technical manual should be an instrument of speed where the reader wishes to find as much info as possible, as quick as possible, with as little in the way as possible". I came across the previous statement yesterday over here and I intend to describe more about the incident/accident in a later post, but that particular statement summarises exactly what I have been thinking all along but was very vague about. I have decided that henceforth, whatever technical articles/posts/manuals I write, I will try my best to make it an "instrument of speed" (starting with this one). Now, as I have mentioned previously, here and here "everything in lisp is a function". In this post, I will guide you in creating your own functions from scratch. First, the template for creating a function :
Code :
(defun function_name (args)
  "documentation"              ;optional
  (interactive optional-args)  ;optional
  body)

The defun is a special form and it contains the arguments "documentation" as well as (interactive args) which are optional as indicated in the code above. The body may contain one or more expressions. Let's start with a simple example that uses the message function described here and here.
Code :
(defun hello()                ;no arguments for hello
   (message "Hello World!")) 

To execute your newly created function first execute the defun form above then execute (hello) as
Code :
(hello)

When you type in C-h f you get the hello function but no documentation. Let's document the function hello(),
Code :
(defun hello()
    "Prints Hello World into the echo area"
   (message "Hello World!"))

You want to make it interactive? Well, write it as
Code :
(defun hello()
    "Prints Hello World into the echo area"
    (interactive)
   (message "Hello World!"))

Now, with arguments
Code :
(defun hello-person(user)
    "Greets the user"
    (interactive)
   (message "Hello %s" user))

(hello-person user-full-name)

Finally, a neat little function (execute it and see)

Code :
(defun my-function()
   (goto-char (point-max))
   (insert "\nhi There !"))

(my-function)


0 comments:

Post a Comment