Clojure multimethods global hierarchy - clojure

In the docs it says
All of the examples above use the global hierarchy used by the multimethod system
What is the global hierarchy ?

Check out core.clj and look for (def ^{:private true} global-hierarchy (make-hierarchy)). The doc string for make-hierarchy says
"Creates a hierarchy object for use with derive, isa? etc."
The relationship of this with multimethod system can be find out by doing a macroexpand on defmulti which results in a call to clojure.lang.MultiFn constructor with the method name as string and also the var #'clojure.core/global-hierarchy. You can look into clojure.lang.MultiFn source if you want but that is "under the hood" of multimethods.

Related

How do I abstract away implementation details in Clojure?

I'd like to hide the details of my persistence layer behind some sort of interface. In Java I would just create an interface and choose the correct implementation in some sort of bootup function. I'm still struggling on how to do that in Clojure. I don't necessarily need any type-safety here, I trust in my unit tests to find any issues there. The best thing I could come up with was to create a map containing anonymous functions with specific keys, like so:
(def crux-db {
:get-by-id (fn [id] (get-obj...))
:save (fn [id obj] (store-obj...))
})
(def fs-db {
:get-by-id (fn [id] (get-obj...))
:save (fn [id obj] (store-obj...))
})
If I'm not missing something, this would allow me to replace the database implementation by def-ing (def db crux-db) or (def db fs-db), as long as all the functions exist in all implementation maps. Somehow I feel like this is not the clojure way but I can't put my finger on it. Is there another way to do this?
Protocols are a way to do that. They let you define what functions should be there. And
you can later implement them for different things with e.g.
a defrecord.
A protocol is a named set of named methods and their signatures, defined using defprotocol:
(defprotocol AProtocol
"A doc string for AProtocol abstraction"
(bar [a b] "bar docs")
(baz [a] [a b] [a b c] "baz docs"))
No implementations are provided
Docs can be specified for the protocol and the functions
The above yields a set of polymorphic functions and a protocol object
all are namespace-qualified by the namespace enclosing the definition
The resulting functions dispatch on the type of their first argument, and thus must have at least one argument
defprotocol is dynamic, and does not require AOT compilation
defprotocol will automatically generate a corresponding interface, with the same name as the protocol, e.g. given a protocol my.ns/Protocol, an interface my.ns.Protocol. The interface will have methods corresponding to the protocol functions, and the protocol will automatically work with instances of the interface.
Since you mentioned crux in your code, you can have a peek at how they
use it
here
and then using defrecords to implement some of
them
There are several ways to achieve this. One way would be to use protocols. The other way would be to just use higher-order functions, where you would "inject" the specific function and expose it like so:
(defn get-by-id-wrapper [implementation]
(fn [id]
(implementation id)
...))
(defn cruxdb-get-by-id [id]
...)
(def get-by-id (get-by-id-wrapper cruxdb-get-by-id))
Also worth mentioning here are libraries like component or integrant which are used to manage the lifecylce of state.

Dynamically computing gen-class

Clojure's java interop is good but often bridging between an object oriented java API (especially one requiring subclassing, annotations, and state) and clojure code is awkward. To make this easier, I had a thought to try to provide a wrapper such that I could write something like this:
(component "Foo"
(handler "bar"))
and by implementing component and handler as macros I could return something uglier but correct like:
(gen-class
[component-name]
:name ^{Component {}} (str "com.foobar." component-name)
:implements [com.foobar.api.SomeInterface]
:main false
:constructors {[com.foobar.data.SomeData]} []}
...
However, while it appears that my component macro would expand to the code above, gen-class appears to be a special form that is sought during compilation and parsed without evaluating its "child forms". This means that forms like (str "com.foobar." component-name) are not evaluated and the generated class is actually ./(str "com/foobar/" name).class
Is there anyway I can create a little DSL to generate java classes like this?

What is reify in Clojure?

I could not understand the usage of reify function in Clojure.
What is it used for in clojure?
Could you provide examples?
reify is to defrecord what fn is to defn.
"Ah right...... so what's reify"
Put simply, protocols are lists of functions a datatype should support, records are datatypes and reifications are anonymous datatypes.
Maybe this is long-winded, but reify can't be understood concretely without understanding protocols and types/records: Protocols are a way to use the same name for a function such as conj that actually acts differently when given different arguments ((conj [:b :c] :a) => [:b :c :a] but (conj '(:b :c) :a) => (:a :b :c)). Records are like objects or types (but they act like maps making them awesomer).
More fundamentally, the goal is to solve "The Expression Problem" that is to have the ability to seamlessly add new types of data that work with existing functions, and new functions that work seamlessly with existing data.
So one day you say to yourself, "Self, you should learn what it means to be a duck!" so you write a protocol:
(defprotocol Quacks
(quack [_] "should say something in ducky fashion"))
But it's all too abstract so you 'realify' it:
(def donald (reify Quacks
(quack [_] "Quacks and says I'm Donald")))
Now at last you can experience your creation:
(quack donald) => "Quacks and says I'm Donald"
Then you remember about Daffy:
(def daffy (reify Quacks
(quack [_] (str "Quacks and says I'm Daffy"))))
(quack daffy) => "Quacks and says I'm Daffy"
But by the time you remember about Huey, you realize your mistake and define what a duck is in a reusable way:
(defrecord Duck [name]
Quacks
(quack [_] (str "Quacks and says I'm " name)))
And make new ducks (there are several ways to do it):
(def huey (->Duck "Huey"))
(def duey (Duck. "Duey"))
(def louie (new Duck "Louie"))
(quack huey) => "Quacks and says I'm Huey"
Remember that records act like maps (thank to protocols!):
(:name huey) => "Huey"
But then you remember that ducks must quack and walk so you write another protocol:
(defprotocol Walks
(walk [_] "should walk like a duck"))
And extend the definition of duck
(extend-type Duck
Walks
(walk [_] "waddle waddle"))
(walk louie) => "waddle waddle"
Now we can extend other types to implement the same protocol (teach the same function how to work with other things):
So let's say we want programmers to quack too :-)
(defrecord Programmer [] Quacks
(quack [_] "Monads are simply monoids in a category of endofunctors..."))
(quack (Programmer.)) => "Monads are simply monoids in a category of endofunctors..."
I recommend this great explanation of protocols, an explanation of reify and a chapter on protocols in "Clojure for the Brave and True".
Disclaimer: This is only meant to give an initial understanding of what protocols are, not best practices on how to use them. "Psst! I answered this question largely to teach myself, because until yesterday I had never actually written my own protocol/interface!"
So while I hope that it enhances someone else's learning, I'll heartily welcome criticism or edit-suggestions!".
reify macro allow to create an anonymous class extending java.lang.Object class and/or implementing specified interfaces/protocols. The API docs don't describe the purpose clearly but rather provide the technical details what that macro does. Java interop documentation provides a brief description of the purpose:
As of Clojure 1.2, reify is also available for implementing
interfaces.
Even more information can be found in datatypes documentation where you can find a very detailed description what it does and how it compares to proxy:
While deftype and defrecord define named types, reify defines both an
anonymous type and creates an instance of that type. The use case is
where you need a one-off implementation of one or more protocols or
interfaces and would like to take advantage of the local context. In
this respect it is use case similar to proxy, or anonymous inner
classes in Java.
The method bodies of reify are lexical closures, and can refer to the
surrounding local scope. reify differs from proxy in that:
Only protocols or interfaces are supported, no concrete superclass.
The method bodies are true methods of the resulting class, not
external fns. Invocation of methods on the instance is direct, not
using map lookup. No support for dynamic swapping of methods in the
method map. The result is better performance than proxy, both in
construction and invocation. reify is preferable to proxy in all cases
where its constraints are not prohibitive.

How do I tag a Clojure function so that I could recognize it with Java reflection

I need to somehow tag certain Clojure functions as "special" so that Java code could recognize them as such using reflection. I've tried to add an annotation to a function, but apparently that's not supported. I've tried to reify an interface extending IFn (so that the Java code could recognize the function object), but that's no good because Clojure doesn't directly use the reified method as the code implementing invoke, but rather an indirect call to an Afunction object that's actually implementing the method (I need to tag the actual invoke method with the actual function code).
Any ideas?
EDIT: even tagging in a way that could be accessed with the ASM library (rather than regular reflection) would be fine, but I need to somehow tag the actual AFunction object or the invoke method. Also, I can't access the actual AFunction object -- I need the tag to be visible on the class.
You can use clojure meta-data feature which allows meta data (a map) to be attached to any object that implements IMeta interface (which turns out to be every object as IObj extends IMeta and every object extend IObj)
Now there are 2 options.
1) You can attach the meta data to a var (the var points to the actual IFn object)
(defn hello {:name "hello"} [] 10)
and on Java side you get hold of the var hello and use IMeta methods to get the meta data and detect if your specific meta data is there or not.
The problem with this may be that your Java code access/handle IFn objects directly rather than their vars (ex: Anonymous functions), to solve this try the 2nd option.
2) Attach the meta data to the function object itself:
(def hello (with-meta (fn [] 10) {:name "hello"}))
You cannot use defn as that attach meta data to the var. The above sample code attach the meta data to the function object itself. On Java side, typecase the function object to IMeta and do the check.
The above code can be made a bit more defn likish with a help of a macro which is left as an exercise :)
It turns out that if you enclose the function body with a let statement containing a local definition, that variable name will appear in the method's local table in the class file. A bit cumbersome, though. Still looking for a better way.

How does clojure's defrecord method name resolution work?

After defining a record and the interfaces it implements, I can call its methods either by its name or using the java interop way using the dot operator.
user=> (defprotocol Eat (eat [this]))
Eat
user=> (defrecord animal [name] Eat (eat [this] "eating"))
user.animal
user=> (eat (animal. "bob"))
"eating"
user=> (.eat (animal. "bob"))
"eating"
user=>
Under the surface, what is going on there? Are there new clojure functions being defined? What happens when there are functions you defined that share the same name (is this possible?), how are these ambiguities resolved?
Also, is it possible to "import" java methods for other java objects so that you do not need the . operator so that behavior is like above? (For the purpose, for example, of unifying the user interface)
When you define a protocol, each of its methods are created as functions in your current namespaces. It follows that you can't have two protocols defining the same function in the same namespace. It also means that you can have them in separate namespaces and that a given type can extend both[1] of them without any nameclash because they are namespaced (in opposition to Java where a single class can't implement two interfaces with homonymous methods).
From a user perspective, protocol methods are no different from plain old non-polymorphic functions.
The fact that you can call a protocol method using interop is an implementation detail. The reason for that is that for each protocol, the Clojure compiler creates a corresponding backing interface. Later on when you define a new type with inline protocol extensions, then this type will implement these protocols' backing interfaces.
Consequently you can't use the interop form on an object for which the extension hasn't been provided inline:
(defrecord VacuumCleaner [brand model]
(extend-protocol Eat
VacuumCleaner
(eat [this] "eating legos and socks"))
(.eat (VaacumCleaner. "Dyson" "DC-20"))
; method not found exception
The compiler has special support for protocol functions so they are compiled as an instance check followed by a virtual method call, so when applicable (eat ...) will be as fast as (.eat ...).
To reply to "can one import java methods", you can wrap them in regular fns:
(def callme #(.callme %1 %2 %3))
(obviously you may need to add other arities to account for overloads and type hints to remove reflection)
[1] however you can't extend both inline (at least one of them must be in a extend-* form), because of an implementation limitation