Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should I use 'apply' in Clojure?

Tags:

clojure

lisp

This is what Rich Hickey said in one of the blog posts but I don't understand the motivation in using apply. Please help.

A big difference between Clojure and CL is that Clojure is a Lisp-1, so funcall is not needed, and apply is only used to apply a function to a runtime-defined collection of arguments. So, (apply f [i]) can be written (f i).

Also, what does he mean by "Clojure is Lisp-1" and funcall is not needed? I have never programmed in CL.

Thanks

like image 624
unj2 Avatar asked Aug 10 '09 20:08

unj2


People also ask

Does Clojure have closures?

This is a perfect opportunity to enforce encapsulation to avoid drowning the client in board-implementation details. Clojure has closures, and closures are an excellent way to group functions (Crockford 2008) with their supporting data.


1 Answers

You would use apply, if the number of arguments to pass to the function is not known at compile-time (sorry, don't know Clojure syntax all that well, resorting to Scheme):

(define (call-other-1 func arg) (func arg)) (define (call-other-2 func arg1 arg2) (func arg1 arg2)) 

As long as the number of arguments is known at compile time, you can pass them directly as is done in the example above. But if the number of arguments is not known at compile-time, you cannot do this (well, you could try something like):

(define (call-other-n func . args)   (case (length args)     ((0) (other))     ((1) (other (car args)))     ((2) (other (car args) (cadr args)))     ...)) 

but that becomes a nightmare soon enough. That's where apply enters the picture:

(define (call-other-n func . args)   (apply other args)) 

It takes whatever number of arguments are contained in the list given as last argument to it, and calls the function passed as first argument to apply with those values.

like image 101
Dirk Avatar answered Sep 25 '22 01:09

Dirk