Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Discussion] Patterns for monads #113

Open
sukima opened this issue Jul 13, 2014 · 0 comments
Open

[Discussion] Patterns for monads #113

sukima opened this issue Jul 13, 2014 · 0 comments

Comments

@sukima
Copy link
Contributor

sukima commented Jul 13, 2014

In my recent ventures into learning more functional styled programming I'm quite fascinated with monads. Both in terms of compositions and readability (A.K.A chaining). This got me thinking on how to pattern this style.

Sure, there are many libraries out there that attempt to make monads through programmatic means (currying I think it's calls). However, in my research the concept for a monad is simple enough one shouldn't need a library to implement.

What I mean is, couldn't there be a pattern one could use to make monads in their programs? I'll discuss a few examples here in hopes to illicit some discussion on possible patterns suitable for the cookbook. (The example are a rough draft I whipped up while writing this).

Identity

Simplest example although not very useful (I think).

class Identity
  constructor: (@value) ->
    @value = @value.value if @value instanceof Identity
  bind: (fn) ->
    newValue = fn.call(this, @value)
    new Identity(newValue)

Maybe

An example with some practical usage. The Maybe Monad encapsulates a value allowing functions to be composed on it without need for a

class Maybe
  constructor: (@value) ->
    @value = @value.value if @value instanceof Maybe
  bind: (fn) ->
    return this unless @value?
    newValue = fn.call(this, @value)
    new Maybe(newValue)

Immutable Object

This is the heart of the issue here, using OOP style classes in a functional / immutable way.

class MyObject
  constructor: (@value) ->
    @value = @value.value if @value instanceof MyObject
  bind: (fn) ->
    newValue = fn.call(this, @value)
    new MyObject(newValue)
  addTwo: ->
    @bind =>
      @value + 2

This isn't to compete with promises which are much better off being handled via a library but I think there is some advantages to modeling your typical classes as monadic classes providing a chainable and readable way to compose functions on itself and providing immutability to what would otherwise be mutable OOP.

Thoughts? Ideas?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant