Skip to content

Instantly share code, notes, and snippets.

@kolharsam
Forked from lispyclouds/monads.clj
Created May 17, 2020 02:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kolharsam/c00a5395cb0b2f9176499d281290dc41 to your computer and use it in GitHub Desktop.
Save kolharsam/c00a5395cb0b2f9176499d281290dc41 to your computer and use it in GitHub Desktop.
Monads, simple made easier
; A simple demo of monadic composition of side effects
; Program to take 3 nubers as input and print their sum.
(defn read-and-add!
[prev]
(print "Enter a number: ")
(+ prev (do (flush)
(Integer/parseInt (read-line)))))
(defn bind
[m next-fn]
(try
(next-fn m)
(catch Exception e (reduced (str e)))))
(defn chain
[init & effects]
(reduce bind init effects))
(println (chain 0
read-and-add!
read-and-add!
read-and-add!))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment