4 ms·
The problem with monads is that its hard to justify the whole concept until you start wanting abstract some code to work with more then one monad. That said, s
by ufo 14y ago
The problem with monads is that its hard to justify the whole concept until you start wanting abstract some code to work with more then one monad.
That said, specific monads actually show up pretty often. A very important example is the Promise monad used by some Javascript async libraries:
(for example, see https://github.com/kriskowal/q https://github.com/kriskowal/q or http://dojotoolkit.org/documentation/tutorials/1.6/promises/ http://dojotoolkit.org/documentation/tutorials/1.6/promises/)
Basically, creating a new promise is the monadic "return" and the "promise.then" method is the monadic "bind" (or "fmap", if the callback returns a normal value instead). I found that knowing a bit about monads helped me work better with the promises from the Dojo framework but I guess your mileage may vary...
- Peaker 14y agoGeneralizing Monad in a language without return-type polymorphism is hard. How do you implement "return" (unit)?
- tikhonj 14y agoThe best way would be to specify the return type directly. This is unfortunate, but it is how basically any language (that I know) save Haskell would do it. So instead of having a return function, you would use something like List.return or Maybe.return or whatever. This is the same way you would solve the problem of read (that is, the opposite of toString): Double.parse, Integer.parse and so on. When you have a polymorphic function, you would pass in the type as appropriate. Clearly, this is not ideal. However, this is basically what the Haskell compiler does for you with typeclasses--loosely speaking, a function polymorphic over a typeclass gets transformed into a function accepting an instance and its normal arguments. In OCaml, you could solve this problem with a functor. So your polymorphic module is parametrized on another module that provides the return and bind functions. I personally like this approach less than Haskell's, but it is more flexible (for better or worse): you can have different modules passed in for the same type. In Haskell, to get different behavior for the same type using typeclasses, you'd have to create a new type with newtype. So in short, it isn't impossible: you just have to do more manually than you do in Haskell.
- Peaker 14y agoIf you want to write functions that are polymorphic on any monad, they'd have to take a type argument explicitly, which also reduces their cost-effectiveness. I am not sure Monads are a cost-effective abstraction in most languages.