|
In Ruby and many other languages, you have this idea of a string concatenation: "foo" + "bar" -> "foobar"
"foo" + "" -> "foo"
That makes it a monoid. Instead of talking about OOP patterns, knowing that the "+" operator is a monoid for string objects lets us write code that is composable.Similarly, with arrays: [:foo,:bar] + [:baz] -> [:foo,:bar,:baz]
[:foo,:bar] + [] -> [:foo,:bar]
Some language platforms will implement the first concat, but not the latter. Without the latter, you couldn't do things like, accept an empty user input. You would have to write code like: defaults + user_input unless user_input_array.empty?
This applies to things like, hashes, or even more complex objects -- such as ActiveRecord named scopes, even if they don't use a "+" operator. (But maybe, Hash objects can be "+" together instead of calling merge())This is all applicable to how you can design libraries and DSLs that seem intuitive and easy to use. Instead of just thinking about bundling a number of methods together with a data structure, you can make sure that a single method within that bundle works the way you expected across a number of objects. You might even be using these ideas in your code, but don't realize it. |
Where is Category Theory?