Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Monads and Decorator pattern

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 ?

like image 774
Prasad Weera Avatar asked Sep 04 '12 08:09

Prasad Weera


People also ask

Is a monad a Decorator?

Monads are definitely not decorators.

What is monad pattern?

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.

What are monads explain with example?

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.

What is Decorator pattern in design pattern?

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.


2 Answers

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.:

  • http://logicaltypes.blogspot.sg/2011/09/monads-in-java.html

The best Clojure-based monad tutorial I know of is this video series by Brian Marick:

  • https://vimeo.com/20717301

I suggest watching this through - it's a pretty good introduction with lots of examples.

like image 163
mikera Avatar answered Sep 27 '22 23:09

mikera


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

like image 45
jdevelop Avatar answered Sep 27 '22 22:09

jdevelop