Defining Local Functions in Lisp

We define local functions using the flet command. The flet command has the following structure:

 (flet ((function_name (arguments)
          ...function body...))
   ...body...)

At the top of the flet, we declare a function (in the first two lines). This function will then be available to us in the body . A function declaration consists of a function name, the arguments to that function , and the function body , where we put the function’s code.

Here is an example:

 > (flet ((f (n)
             (+ n 10)))
     (f 5))
  15

In this example, we define a single function, f, which takes a single argument, n . The function f then adds 10 to this variable n , which has been passed in it. Then we call this function with the number 5 as the argument, causing the value 15 to be returned .

As with let, you can define one or more functions within the scope of the flet.

A single flet command can be used to declare multiple local functions at once. Simply add multiple function declarations in the first part of the command:

 > (flet ((f (n)
            (+ n 10))
          (g (n)
            (- n 3)))
    (g (f 5)))
  12

Here, we have declared two functions: one named f and one named g . In the body of the flet, we can then refer to both functions. In this example, the body first calls f with 5 to yield 15, then calls g to subtract 3, leading to 12 as a final result.

To make function names available in defined functions, we can use the labels command. It’s identical in its basic structure to the flet command. Here’s an example:

 > (labels ((a (n)
              (+ n 5))
            (b (n)
               (+ (a n) 6)))
    (b 10))
  21

In this example, the local function a adds 5 to a number . Next, the function b is declared . It calls the function a, and then adds 6 to the result . Finally, the function b is called with the value 10 . Since 10 plus 6 plus 5 equals 21, the number 21 becomes the final value of the entire expression. The special step that requires us to use labels instead of flet is where the function b calls the function a . If we had used flet, the function b would not have “known” about the function a.

The labels command lets you call one local function from another, and it allows you to have a function call itself. This is commonly done in Lisp code and is called recursion. (You will see many examples of recursion in future chapters.)

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.139.169