Skip to content

Instantly share code, notes, and snippets.

@orionll
Created April 27, 2015 11:59
Show Gist options
  • Select an option

  • Save orionll/723161bab1a32f0ae248 to your computer and use it in GitHub Desktop.

Select an option

Save orionll/723161bab1a32f0ae248 to your computer and use it in GitHub Desktop.
Calculate string length with the Reader monad
import qualified Control.Monad.Trans.Reader as R
strLength :: R.Reader String Int
strLength = do
s <- R.ask
case s of
[] -> return 0
(_:cs) -> fmap (+1) (R.local (const cs) strLength)
main = do
print (R.runReader strLength "abc") -- 3
print (R.runReader strLength "abcde") -- 5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment