Monads/Writer monad: Difference between revisions
alphabetize, minor clean-up
Thundergnat (talk | contribs) (alphabetize, minor clean-up) |
|||
Line 10:
# Derive Writer monad versions of each of these functions
# Apply a composition of the Writer versions of root, addOne, and half to the integer 5, deriving both a value for the Golden Ratio φ, and a concatenated log of the function applications (starting with the initial value, and followed by the application of root, etc.)
=={{header|ALGOL 68}}==
Line 722 ⟶ 721:
added one: 2.236068 -> 3.236068
halved it: 3.236068 -> 1.618034
</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();</lang>▼
{{out}}▼
<pre>▼
Result = 1.61803▼
init → 5▼
root → 2.23607▼
inc → 3.23607▼
half → 1.61803▼
</pre>▼
<lang zkl>w:=Writer(5.0);▼
Utils.Helpers.fcomp(w.half,w.inc,w.root)(w).println(); // half(inc(root(w)))</lang>▼
{{out}}▼
<pre>▼
Result = 1.61803▼
init → 5▼
root → 2.23607▼
inc → 3.23607▼
half → 1.61803▼
</pre>▼
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▼
+ 1 → 3.23607▼
/ 2 → 1.61803▼
</pre>
Line 822 ⟶ 776:
add one: 3.2360679774998
half: 1.6180339887499
▲</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();</lang>
▲{{out}}
▲<pre>
▲Result = 1.61803
▲ init → 5
▲ root → 2.23607
▲ inc → 3.23607
▲ half → 1.61803
▲</pre>
▲<lang zkl>w:=Writer(5.0);
▲Utils.Helpers.fcomp(w.half,w.inc,w.root)(w).println(); // half(inc(root(w)))</lang>
▲{{out}}
▲<pre>
▲Result = 1.61803
▲ init → 5
▲ root → 2.23607
▲ inc → 3.23607
▲ half → 1.61803
▲</pre>
▲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
▲ + 1 → 3.23607
▲ / 2 → 1.61803
</pre>
|