Is a self-recursive clojure multimethod a good design for a nested classification problem?

498 views Asked by At

I have a large sequence of data-maps and each map needs to be classified in a nested fashion.

i.e. a given item may be an A or a B (as determined by a function), if it is a B then it may be a C or a D (determined by another function) and so on down. At each stage more data relating to the classification may be added to each map. The functions to do the classification are themselves quite complex and may need to bring in additional data to make the determinations.

Would a self-recursive multimethod be a good way to structure the code to do this? I would dispatch on the most specific type so far determined for an item, or return the best current classification when nothing further can be done.

I could get the desired effect with nested ifs inside a single classification function but gosh is that ugly.

Is a multimethod a good fit here or am I over-complicating things and missing a simpler way of structuring the code?

2

There are 2 answers

1
Alex Miller On BEST ANSWER

Seems like multimethods might be useful here. I guess all the complexity is in the dispatch function? So once you classify the top level you fire the multimethod again with more info that triggers a different instance?

Another way to think this is to base it around traversing the decision tree instead of traversing your input. I wonder whether using clojure.zip to traverse a tree of classification functions might be an interesting solution. Your classification function at each node could tell you how to next traverse the tree (which child to go to). You wouldn't need clojure.zip necessarily but it has the tree navigation in it already.

0
Arthur Ulfeldt On

multimethods are great because they allow this level of dispatch when the complexity of the problem calls for it. I say go for it if it does what you want.

Perhaps you could build an isa hierarchy to help