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.
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.
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.
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.
Use a let
or letfn
:
(fn [x y]
(let [diff (... function body here ...)]
(set
(concat (diff x y) (diff y x)))))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With