What is the idiomatic Haskell solution for dependency injection?
E.g., suppose you have an interface frobby, and you needed to pass an instance conforming to frobby around (there might be multiple varieties of these instances, say, foo, and bar).
Typical operations would be:
-
functions that take some value
Xand return some valueY. E.g., this might be a database accessor, taking a SQL query & a connector and returning a dataset. You might need to implement postgres, mysql, and a mock test system. -
functions that take some value
Zand return a closure relating toZ, specialized to a givenfooorbarstyle, chosen at runtime.
One person solved the problem as follows:
http://mikehadlow.blogspot.com/2011/05/dependency-injection-haskell-style.html
But I don’t know if that’s the canonical way to manage this task.
I think the proper answer here is, and I will probably receive a few downvotes just for saying this: forget the term dependency injection. Just forget it. It’s a trendy buzzword from the OO world, but nothing more.
Let’s solve the real problem. Keep in mind that you are solving a problem, and that problem is the particular programming task at hand. Don’t make your problem “implementing dependency injection”.
We’ll take the example of a logger, because that’s a basic piece of functionality many programs will want to have, and there are lots of different types of loggers: One that logs to stderr, one that logs to a file, a database, and one that simply does nothing. To unify all them you want a type:
You could also choose a fancier type to save some keystrokes:
Now let’s define a few loggers using the latter variant:
You can see how this builds a graph of dependencies. The
acidLoggerdepends on a database connection for theMyDBdatabase layout. Passing arguments to functions is about the most natural way to express dependencies in a program. After all a function is just a value that depends on another value. That is also true for actions. If your action depends on a logger, then naturally it is a function of loggers:See how easy this is? At some point this makes you realize how much easier your life will be, when you just forget all the nonsense that OO has taught you.