top | item 8310377

(no title)

elclanrs | 11 years ago

In dynamic languages I don't see the need to create a Monad interface. I'd create classes/objects and simply use instances of those objects. As long as they conform to the desired interface, and you can check their relationships, then it should work; and use monkey-patching if necessary, embracing the dynamic nature of the language. I don't think it is possible to fully translate Haskell examples without the types, but you can adapt the ideas to other languages and get very similar functionality, in JavaScript for example:

    class Maybe {
      constructor(value) {
        if (value != null) {
          return new Just(value)
        }
        return new Nothing()
      }
      bind(f) {
        if (this instanceof Just) {
          return f(this.value)
        }
        return new Nothing()
      }
    }

    class Just extends Maybe {
      constructor(value) {
        this.value = value
      }
      toString() {
        return `<Just ${this.value}>`
      }
    }

    class Nothing extends Maybe {
      constructor() {
        this.value = null
      }
      toString() {
        return '<Nothing>'
      }
    }

    var result = Maybe(2).bind(x => {
      return Maybe(3).bind(y => {
        return Maybe(x + y)
      })
    })

    console.log(result.toString()) // <Just 5>

discuss

order

No comments yet.