You should be automatically redirected . If not, visit
and update your bookmarks.


Is this the right room for an argument?

One of the pleasant things about Lisp is the arguments. No, not the sort of argument that you'll find on Planet Lisp, I mean the way you supply information to functions. For those of us more familiar with other languages, Lisp seems very casual about the whole business.

For example, you'd expect to be able to do this:

(+ 2 2) ;-> 4

but being able to do this seems odd at first:

(* 2) ;-> 2

but then it's nice to be able to do this:

(div 1 2 3 4 5 6) ;-> 0.001388888889

I think you can supply any number of arguments to a Lisp function.

You can also define functions using this very casual approach to specifying how many arguments are required. Say I want to write a simple mean command. This would be a good start:

(define (mean num-list)
    (div    (apply add num-list)
            (length num-list)))
(println (mean '(1 2 3 4 5 6 7 8 9 10))) ;-> 5.5

The apply function adds the list argument, then the sum is divided by the length of the list.

Another way to do this is to use the args function. This accesses the arguments passed to the function.

(define (mean)
    (if (args) 
        (div    (apply add (args)) 
                (length (args)))))

which lets us type any of the following:

(mean)                             ;-> ( )
(mean 1)                           ;-> 1
(mean 1 2)                         ;-> 1.5
(mean 1 2 3 4 5 6 7 8 9 10)        ;-> 5.5

which is more flexible. And newLISP offers even more ways of specifying arguments to functions, and things can get more complicated when you start using macros and lambda expressions.

But at this level, the hardest thing is to remember and make use of the flexibility offered.


Post a Comment

Links to this post:

Create a Link

<< Home