A record can implement protocols. However, each time I think of a new function that I would like the record to implement, I have to add it to an existing protocol or create a new protocol. How do I get around this? Ideally, I'd just like to associate a function to a record without having to define a protocol.
- Anybody can ask a question
- Anybody can answer
- The best answers are voted up and rise to the top
Then just write a function that takes an instance of that record as an argument.
defrecord doesn't "implement" a protocol, in the sense that class in a Java-like OO language implements an interface. What it does is define a datatype, and give you some syntactic sugar to implement a protocol that operates on that datatype. There's a pretty great overview of just what sort of problem protocols are meant to solve here - http://www.ibm.com/developerworks/library/j-clojure-protocols/
Excellent question. Here's an answer based on a similar one I gave on StackOverflow.
As usual, there's a beautiful way to do things in Clojure - here's how to implement your own simple dynamic OO system (including inheritance, polymorphism and encapsulation) in 10 lines of Clojure.
The idea: You can put functions inside normals Clojure maps or records if you want, creating an OO-like structure. You can then use this in a "prototype" style.