I'm new to functional programming. While following a tutorial on Monads, I got to think it as the analogy of Decorator pattern in OOP. Am I correct or is there any design pattern that closely resembles Monads ?
Monads are definitely not decorators.
In functional programming, a monad is a software design pattern with a structure that combines program fragments (functions) and wraps their return values in a type with additional computation.
Monads are simply a way to wrapping things and provide methods to do operations on the wrapped stuff without unwrapping it. For example, you can create a type to wrap another one, in Haskell: data Wrapped a = Wrap a. To wrap stuff we define return :: a -> Wrapped a return x = Wrap x.
In object-oriented programming, the decorator pattern is a design pattern that allows behavior to be added to an individual object, dynamically, without affecting the behavior of other objects from the same class.
Monads are definitely not decorators. There isn't a standard OOP pattern in common use that is a direct analogy of monads. Though you can implement monads in OOP just fine, see e.g.:
The best Clojure-based monad tutorial I know of is this video series by Brian Marick:
I suggest watching this through - it's a pretty good introduction with lots of examples.
you can start thinking about monads as about "overridable semicolons", due to the known syntax-sugar in Haskell
in general, that does mean you can have same control structure (code block) doing different things depending on which monad is currently used
qick example in Haskell
import Data.Maybe
import Data.List
funcMaybe x = do
z <- x
return $ z * z
funcList x = do
z <- x
return $ z * z
runMaybe = funcMaybe ( Just 5 )
runList = funcList [ 5, 6 ]
being executed in GHCI, it will prompt
ghci> runMaybe
Just 25
ghci> runList
[25, 36]
as you can see, the same code block produces different results - List in one case and Maybe in another case, wrapped into appropriate data structure
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With