What would an equivalent construct of a monad be in Ruby?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The precise technical definition: A monad, in Ruby, would be any class with
bindandself.unitmethods defined such that for all instances m:Some practical examples
A very simple example of a monad is the lazy Identity monad, which emulates lazy semantics in Ruby (a strict language):
Using this, you can chain procs together in a lazy manner. For example, in the following,
xis a container “containing”40, but the computation is not performed until the second line, evidenced by the fact that theputsstatement doesn’t output anything untilforceis called:A somewhat similar, less abstract example would be a monad for getting values out of a database. Let’s presume that we have a class
Querywith arun(c)method that takes a database connectionc, and a constructor ofQueryobjects that takes, say, an SQL string. SoDatabaseValuerepresents a value that’s coming from the database. DatabaseValue is a monad:This would let you chain database calls through a single connection, like so:
OK, so why on earth would you do that? Because there are extremely useful functions that can be written once for all monads. So code that you would normally write over and over can be reused for any monad once you simply implement
unitandbind. For example, we can define a Monad mixin that endows all such classes with some useful methods:And this in turn lets us do even more useful things, like define this function:
The
sequencemethod takes a class that mixes in Monad, and returns a function that takes an array of monadic values and turns it into a monadic value containing an array. They could beIdvalues (turning an array of Identities into an Identity containing an array), orDatabaseValueobjects (turning an array of queries into a query that returns an array), or functions (turning an array of functions into a function that returns an array), or arrays (turning an array of arrays inside-out), or parsers, continuations, state machines, or anything else that could possibly mix in theMonadmodule (which, as it turns out, is true for almost all data structures).