Monads/Writer monad: Difference between revisions

Content added Content deleted
(Added EchoLisp)
Line 202:
divided by 2 -> 1.618033988749895"
}</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>