Skip to content

[Discussion] Patterns for monads #113

Open
@sukima

Description

@sukima

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?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions