Skip to content

Instantly share code, notes, and snippets.

@belisarius222
Created February 25, 2020 09:27
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save belisarius222/5302bf22a0c1fe2ab298591814559855 to your computer and use it in GitHub Desktop.
Save belisarius222/5302bf22a0c1fe2ab298591814559855 to your computer and use it in GitHub Desktop.
state monad in hoon
=< (do-some-stack-ops ~[1 2 3])
|%
++ do-some-stack-ops
=/ liz (list @)
=/ st (stack @)
=/ m (stat liz @)
^- form:m
;< empty=? bind:m is-empty:st
?. empty
pop:st
;< ~ bind:m (push:st 7)
pop:st
:: +stack: stack library using +stat monad
::
++ stack
|* item=mold
|%
+$ s (list item)
++ push
|= i=item
=/ m (stat s ,~)
^- form:m
;< s0=s bind:m get:m
(put:m i^s0)
::
++ pop
=/ m (stat s item)
^- form:m
;< s0=s bind:m get:m
?~ s0 !!
;< ~ bind:m (put:m t.s0)
(pure:m i.s0)
::
++ is-empty
=/ m (stat s ?)
^- form:m
|= s0=s
[?=(~ s0) s0]
--
:: +stat: state monad
::
:: Really, (stat s) curried is a state monad parameterized on .a.
:: Uncurried was just more convenient.
::
++ stat
|* [s=mold a=mold]
|%
+$ output [a s]
+$ form $-(s [a s])
++ pure
|= a0=a
^- form
|=(s0=s [a0 s0])
::
++ bind
|* b=mold
|= [m-b=$-(s [b s]) fun=$-(b $-(s [a s]))]
^- form
|= s0=s
^- [a s]
=^ res s0 (m-b s0)
((fun res) s0)
::
++ get |=(s0=s [s0 s0])
++ put |=(s0=s |=(s [~ s0]))
--
--
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment