overloaded private function which is private in clojure - clojure

Usually I have the same structure of my functions:
(defn func-name
([] (some actions))
([ar] (some actions))
([ar aar] (some actions)))
And usually only one of this variant is public. But as You can see from my entry - all my function is public because of using defn instead of defn-. But defn- hide all function, including all overloaded.
Is there any way to 'hide' only part of overloaded function?
For example, I want to hide an func-name with arity of one and two arguments.
Ofcorse I can hide overloaded function inside one defn like this:
(defn awesome[]
(let [func (fn some-func ([] (some actions))
([ar] (some actions)))]
(func)))
But I think it's a little bit messy and I'm sure there have to be a way to solve it.
Thanks!

As I know this visibility is defined by :private flag in var's meta. So this two expressions are equal:
(defn ^:private foo [] "bar")
(defn- foo [] "bar")
So I think you can control a visibility only of a whole var.
I can suggest to use different function names for public and private spaces. I.e func-name for public one and func-name- for private.

Related

Performance concern of defining functions in a `let` form

Is there any performance penalty for defining anonymous functions in a let form and calling the outer function repeatedly? Like this:
(defn bar [x y]
(let [foo (fn [x] (* x x))]
(+ (foo x) (foo y))))
Compared to defining foo as a separate function, like this:
(defn foo [x] (* x x))
(defn bar [x y] (+ (foo x) (foo y)))
I understood the lexical scope of foo is different in these two cases, I'm just concerned if the foo function would be defined over and over again when calling bar multiple times.
I guess the answer is no, i.e., there is no penalty for this, but how did clojure do this?
Thank you!
let local approach:
foo is compiled only once (when the top-level form is). The result of this compilation is a class implementing the clojure.lang.IFn interface; the actual body lives in the invoke(Object) method of that class. At runtime, each time control reaches the point in bar where the foo local is introduced, a fresh instance of that class is allocated; the two calls to foo use that instance of that class.
Here is a simple way to prove the "single compilation" property at the REPL:
(defn bar [x y]
(let [foo (fn [x] (* x x))]
foo))
(identical? (class (bar 1 2)) (class (bar 1 2)))
;= true
NB. Clojure is smart enough to notice that foo is not an "actual closure" (it closes over the parameters of bar, but it doesn't actually use them), so the runtime representation of foo does not carry any extra fields that a closure would, but a fresh instance of foo's class is nevertheless allocated on each call to bar.
Separate defn approach:
There is a single instance of foo, however calling it involves an indirection through a Var, which itself comes with a non-zero cost. That cost is generally not worth worrying about in all but the most performance-sensitive code, but it's there, so factoring out a local function may not necessarily be a performance win. As usual, if it's worth optimizing, it's worth measuring/benchmarking first.
let over lambda
There is also the final option mentioned by Daniel, where the let goes around, and not inside, the defn. With that approach, there is a single instance of (the class of) foo; it is stored in a field inside bar; and it is used for all calls to foo inside bar.
The answer is yes, there will be a penalty for this but as Michael points out in the let local approach section, it is minimal.
If you want the lexical scoping as you described, then wrap the let block defining foo around the defn for bar. That will do what you are asking. However it is a pattern not commonly seen in Clojure code.

Checking Clojure pre-conditions without running the function?

I have one function that does some (possibly lengthy) work (defn workwork [x] ...) and some other functions to check if the call will succeed ahead of time (defn workwork-precondition-1 [x] ...).
The precondition functions should be evaluated every time workwork is called (e.g. using :pre). The precondition functions should also be collected (and:ed) in a single function and made available to client code directly (e.g. to disable a button).
Which is the idiomatic way to solve this in Clojure while avoiding code duplication?
In particular, is there any way to evaluate the pre-conditions of a function without running the function body?
You can just collect your preconditions into a function:
(defn foo-pre [x]
(even? x))
Then call the function in a :pre-style precondition:
(defn foo [x]
{:pre [(foo-pre x)]}
…)
For functions introduced using defn, you can extract the :pre-style preconditions from the metadata on the Var:
(-> #'foo meta :arglists first meta)
;= {:pre [(foo-pre x)]}
And similarly for the :arglists entries for any other arities.
There are two caveats here:
The automatically-generated :arglists entry in the Var's metadata maybe be overridden. Overriding :arglists results in the above kind of useful automatically-generated metadata to be thrown out.
The {:pre [(foo-pre x)]} value returned by the above (-> #'foo meta …) expression contains foo-pre as a literal symbol – it'd be your responsibility to figure out which function it referred to at foo's point of definition. (This may or may not be possible – for example foo could be defn'd inside a top-level let or letfn form, with foo-pre a local function.)
And finally, anonymous functions may use :pre and :post, but there is currently no mechanism for extracting them from the function itself.
to evaluate the function precondition without running the function body,you can use robert-hooke library https://github.com/technomancy/robert-hooke/
(use 'robert.hooke)
(defn workwork [x] ...)
(defn workwork-precondition-1
[f x]
(if (precondition-1-satisfied? x)
(f x)
:precondition-1-not-satisfied))
(add-hook #'workwork #'workwork-precondition-1)

How to make a local type in Clojure?

I want to create a type in Clojure only visible from the current namespace.
Having a type my-type defined in my.ns
(ns my.ns)
(deftype my-type
Protocol
(some-function[]))
How to avoid the usual import strategy, making the type private?
(ns other.ns
(:import my.ns.my-type)
(->my-type)
You cannot prevent your types from being imported, since they are just public classes. You can make the factory functions private like so:
(deftype Foo [])
(alter-meta! #'->Foo assoc :private true)
For a completely hidden "type", you could use reify in a private factory function:
(defn ^:private make-foo [& args]
(reify SomeProtocol
(method1 [this] ...)))
One potential problem here is that you will not be able to use extend-type and similar to augment such a "type".
Protocols, on the other hand, can be made private, with the caveat that their accompanying interfaces will still be public:
(defprotocol ^:private PFoo
(^:private foo [this]))
:private metadata is needed on both the protocol Var and the individual methods, since they receive their own separate Vars. With the above in place, the interface some.ns.PFoo will still be public, but the protocol some.ns/PFoo will not.

Clojure, defn, defn-, public/private, defaults

defn = public
defn- = private
Perhaps I have bad Clojure coding style -- but I find that most functions I write in Clojure are small helper functions that I do not want to expose.
Is there some configuration option, where:
defn = private by default,
and to make something public, I have to do defn+?
Thanks!
No. There is not.
An alternative approach which might or might not work for you is to declare a foo.bar.internal namespace containing all the private helpers which is used by your foo.bar namespace. This has advantages over private function declarations when you want to use private functions in macro expansions.
If the "helper functions" are very likely to be used once, you could choose to make them locals of your bigger functions, or write them as anonymous functions. See letfn: http://clojuredocs.org/clojure_core/clojure.core/letfn and http://clojuredocs.org/clojure_core/clojure.core/fn.
I hardly ever use letfn myself.
The beauty of Clojure being a Lisp, is that you can build and adapt the language to suit your needs. I highly recommend you read On Lisp, by Paul Graham. He now gives his book away for free.
Regarding your suggestion of defn+ vs defn vs defn-. This sound to me like a good case for writing your own Macro. defn is a function and defn- is a macro. You can simply redefine them as you wish, or wrap them in your own.
Here follows a suggestion to implementation, based mainly on Clojure's own implementation - including a simple utility, and a test.
(defmacro defn+
"same as Clojure's defn, yielding public def"
[name & decls]
(list* `defn (with-meta name (assoc (meta name) :public true)) decls))
(defmacro defn
"same as Clojure's defn-, yielding non-public def"
[name & decls]
(list* `defn (with-meta name (assoc (meta name) :private true)) decls))
(defn mac1
"same as `macroexpand-1`"
[form]
(. clojure.lang.Compiler (macroexpand1 form)))
(let [ ex1 (mac1 '(defn f1 [] (println "Hello me.")))
ex2 (mac1 '(defn+ f2 [] (println "Hello World!"))) ]
(defn f1 [] (println "Hello me."))
(defn+ f2 [] (println "Hello World!"))
(prn ex1) (prn (meta #'f1)) (f1)
(prn ex2) (prn (meta #'f2)) (f2) )
As stated by #kotarak, there is no way (as far as I know) to do that, nor is it desirable.
Here is why I dislike defn- :
I found out that when using various Clojure libraries I sometimes need to slightly modify one function to better suit my particular needs.
It is often something quite small, and that makes sense only in my particular case. Often this is just a char or two.
But when this function reuses internal private functions, it makes it harder to modify. I have to copy-paste all those private functions.
I understand that this is a way for the programmer to say that "this might change without notice".
Regardless, I would like the opposite convention :
always use defn, which makes everything public
use defn+ (that doesn't exist yet) to specify to the programmer which functions are part of the public API that he is supposed to use. defn+ should be no different from defnotherwise.
Also please note that it is possible to access private functions anyway :
;; in namespace user
user> (defn- secret []
"TOP SECRET")
;; from another namespace
(#'user/secret) ;;=> "TOP SECRET"

Can I define a Clojure protocol with methods starting with ":"?

I would like to provide some methods for a clojure protocol starting with the : character. Is there any way to override this in Clojure?
Don't think so. Clojure keywords are implemented in the reader and I don't think there's any way of overriding that behavior.
When you use a keyword as a function, that is equivalent to (get arg :keyword). You can extend what that does by implementing ILookup in your protocol.
Joost.
Sounds like a bad idea: colons are reserved for keywords so even if you could do this I think it would make for some confusing code.
You can of course, put a function inside a record mapped by a keyword:
(defrecord Foo [])
(def foo (Foo. nil {:method (fn [a b] (* a b))}))
((:method foo) 7 10)
=> 70
I've found this to be a useful trick sometimes......