Monads/Writer monad: Difference between revisions
Content deleted Content added
Added EchoLisp |
→{{header|JavaScript}}: Added zkl |
||
Line 202: | Line 202: | ||
divided by 2 -> 1.618033988749895" |
divided by 2 -> 1.618033988749895" |
||
}</pre> |
}</pre> |
||
=={{header|zkl}}== |
|||
{{trans|EchoLisp}} |
|||
<lang zkl>class Writer{ |
|||
fcn init(x){ var X=x, logText=Data(Void," init \U2192; ",x.toString()) } |
|||
fcn unit(text) { logText.append(text); self } |
|||
fcn lift(f,name){ unit("\n %s \U2192; %s".fmt(name,X=f(X))) } |
|||
fcn bind(f,name){ lift.fp(f,name) } |
|||
fcn toString{ "Result = %s\n%s".fmt(X,logText.text) } |
|||
fcn root{ lift(fcn(x){ x.sqrt() },"root") } |
|||
fcn half{ lift('/(2),"half") } |
|||
fcn inc { lift('+(1),"inc") } |
|||
}</lang> |
|||
<lang zkl>Writer(5.0).root().inc().half().println(); |
|||
w:=Writer(5.0); |
|||
Utils.Helpers.fcomp(w.half,w.inc,w.root)(w).println();</lang> |
|||
Use bind to add functions to an existing Writer: |
|||
<lang zkl>w:=Writer(5.0); |
|||
root,inc,half := w.bind(fcn(x){ x.sqrt() },"root"), w.bind('+(1),"+ 1"), w.bind('/(2),"/ 2"); |
|||
root(); inc(); half(); w.println();</lang> |
|||
{{out}} |
|||
<pre> |
|||
Result = 1.61803 |
|||
init → 5 |
|||
root → 2.23607 |
|||
inc → 3.23607 |
|||
half → 1.61803 |
|||
Result = 1.61803 |
|||
init → 5 |
|||
root → 2.23607 |
|||
inc → 3.23607 |
|||
half → 1.61803 |
|||
Result = 1.61803 |
|||
init → 5 |
|||
root → 2.23607 |
|||
+ 1 → 3.23607 |
|||
/ 2 → 1.61803 |
|||
</pre> |