Skip to content

Comment on State Monad for the Rest of Usparent

Comments

"Global configuration as a monad" is represented by the Reader monad, which is basically a wrapper over a function that takes a configuration/environment as a parameter and then returns something. It replaces a read-only global configuration.

This is Haskell, but here's a really simple example.

  -- As an ordinary function:
  foo :: Int -> Bool -> Int
  foo n shouldAdd = if shouldAdd then n + 1 else n - 1

  -- Exactly the same, but using the Reader monad
  foo :: Int -> Reader Bool Int
  foo n = do
    shouldAdd <- ask
    return (if shouldAdd then n + 1 else n - 1)
Here's the same thing, but with a record with one boolean in it:
  -- Config: a record with one boolean in it,
  -- and you access it with a function called `shouldAdd`
  data Config = MkConfig { shouldAdd :: Bool }

  foo :: Int -> Config -> Int
  foo n cfg = if shouldAdd cfg then n + 1 else n - 1

  foo :: Int -> Reader Config Int
  foo n = do
    mustAdd <- asks shouldAdd
    return (if mustAdd then n + 1 else n - 1)
It's basically a way to have implicit read-only parameters. You can call a bunch of functions that take a configuration parameter without having to actually pass the configuration as a parameter explicitly. In an object oriented language, you might use classes for this (if not global variables).
AboutSource Built by g1lg1l

Hackerly is an independent reader for Hacker News, built on the public HN API. Not affiliated with Y Combinator.