Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to create a named function in clojure which is only visible in function scope?

In Scheme I can do something like this:

(define (adder)
  (define (one) 1)
  (define (two) 2)
  (+ (one) (two)))

Calling adder results in 3 while calling one will yield an error since one is only visible within the scope of adder.

In Clojure if I do something similar

(defn adder []
  (defn one [] 1)
  (defn two [] 2)
  (+ (one) (two)))

one and two will pollute my namespace since defn uses def internally which creates bindings in the current namespace.

Is there a function/macro which creates named functions in local scope?

The reason for my question is that I got used to the way Scheme works. Naming my local functions that way often makes my code more readable.

like image 389
Adam Arold Avatar asked Nov 28 '22 15:11

Adam Arold


1 Answers

Try letfn:

Takes a vector of function specs and a body, and generates a set of bindings of functions to their names. All of the names are available in all of the definitions of the functions, as well as the body.

 (defn adder []
   (letfn [(one [] 1)
           (two [] 2)]
     (+ (one) (two))))
like image 187
Alex Avatar answered Dec 05 '22 03:12

Alex