Skip to content
Search

Monad

lastmod 2025-08-05created 2016-07-1915 edits

Comment

A functor preserves the meaning of the existing context. Using the example above, if a functor wraps a String type into an Int type, the result is also an Int type. It cannot convert to a different type.

A monad, on the other hand, can convert to a different type. It can wrap a String type into an Int type, apply it to an operation (or function), and then output the result as a Double type.

In a sense, a monad can be said to play a role similar to a cast in C.

Monad Laws

Comparing the monad approaches of Haskell and OCaml

Monads in Haskell: elegant abstraction

  • Monads are a powerful abstraction tool, not merely a concept similar to Promise
  • Code reuse across various contexts (Maybe, [], IO, State) through the Monad type class
  • Generic functions (e.g., sequence, mapM) usable with any monad
  • do notation enables highly readable code
  • Consistently expresses diverse computational contexts with a single pattern

OCaml's different approach: pragmatism

  • Uses the module system and functors instead of type classes
  • Lack of syntactic support (e.g., do notation) makes monadic code more verbose
  • Direct side effects are allowed, so monads are not essential
  • Prefers direct use of option and result types and module-level abstraction
  • Enables code that is easy to understand locally

Differences in language design philosophy

  • Haskell: purely functional, so monads are essential for managing effects
  • OCaml: allows side effects, enabling more direct code
  • Philosophical differences about abstraction, explicitness, and the role of the type system
  • Haskell emphasizes consistency and abstraction; OCaml emphasizes clarity and practicality

Concluding view

  • Haskell's consistent abstraction is especially appealing in complex systems
  • OCaml's direct approach is useful where immediate understanding matters
  • Type classes and syntactic support enable especially elegant code structuring in Haskell
  • Both approaches have their own merits, and the right choice depends on the situation

See also

Favorite site

References


  1. Monad_Programming_with_Scala_Future.pdf ↩

author Zer0 sitemap