Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I define a function within a function in Clojure and reference that function?

Tags:

clojure

I wrote a function to compute the symmetric difference of two sets (one of the problems on the 4clojure site). The function passed the unit tests, but it's not as clean as I would like, given that I have duplicated code.

(fn [x y] (set (concat 
  (keep-indexed #(if (nil? (get y %2)) %2) x)
  (keep-indexed #(if (nil? (get x %2)) %2) y))))

Obviously I would prefer something like:

(fn [x y] (set (concat (diff x y) (diff y x))))

Where the diff function is defined and referenced "inline", but I don't know how to do that in one fn block.

like image 390
Matthew Avatar asked Nov 03 '11 21:11

Matthew


People also ask

What does FN mean in Clojure?

First Class Functions They can be assigned as values, passed into functions, and returned from functions. It's common to see function definitions in Clojure using defn like (defn foo … ​) . However, this is just syntactic sugar for (def foo (fn … ​)) fn returns a function object.

What is def Clojure?

def is a special form that associates a symbol (x) in the current namespace with a value (7). This linkage is called a var . In most actual Clojure code, vars should refer to either a constant value or a function, but it's common to define and re-define them for convenience when working at the REPL.

How do you declare variables in Clojure?

Naming Variables The name of a variable can be composed of letters, digits, and the underscore character. It must begin with either a letter or an underscore. Upper and lowercase letters are distinct because Clojure, just like Java is a case-sensitive programming language.


1 Answers

Use a let or letfn:

(fn [x y]
  (let [diff (... function body here ...)]
   (set
    (concat (diff x y) (diff y x)))))
like image 70
Matt Fenwick Avatar answered Oct 24 '22 05:10

Matt Fenwick