CQRS and functional programming
So, a little while ago, while I was studying Haskell, I decided to implement Greg Young’s SimpleCQRS example in Haskell.
During the last @DDDBE event, I was showing this to Mathias, and he decided to put it on the big screen.
The general response was:
What’s missing from Greg’s example?
And my reply was that nothing was missing. As people seemed to be flabbergasted by this code, I decided to convert it into a blog post.
This is the code:
A little background for the people who don’t know Haskell:
- The
datastatements define all the required commands, events and state; a pipe symbol for the data type means AorB handle :: [Event] -> Command -> [Event]implies that it is a function namedhandlethat takes as parameters an array of events and a command, and it returns an array of Events.handlefirst creates anitemby assigningapply eventsto it, then it passes it into a function namedhandle', which uses pattern matching to figure out whichhandle'to invokeitem(i.e. the state) is eitherNothingorJust Item.applyevents starts out withNothingas the state, and then callsapply'for every event in the events, resulting in the modified state upon applying every event.
I didn’t consider this such a big thing, except for the terseness and the very low signal to noise ratio in the code, but as people seemed to like it I decided to put this in a blog post for your enjoyment.
Have fun!