Pure Danger Tech


navigation
home

Learning Clojure #4: private functions

09 Feb 2010

Sometimes in a Clojure file you just want some helper functions that shouldn’t be exposed outside the namespace. You can create a private function using the special defn- macro instead of defn.

For instance, create a file foo/bar.clj with a public and a private function:

(ns foo.bar)
(defn- sq [x] (* x x))
(defn sum-squares [a b] (+ (sq a) (sq b)))

Then use it from the REPL:

user=> (use 'foo.bar)
nil
user=> (sum-squares 3 4)
25
user=> (sq 5)
java.lang.Exception: Unable to resolve symbol: sq in this context (NO_SOURCE_FILE:6)