Monads/Writer monad: Difference between revisions
m
syntax highlighting fixup automation
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
|||
Line 13:
=={{header|ALGOL 68}}==
{{Trans|Go}}
<
MODE MWRITER = STRUCT( LONG REAL value
, STRING log
Line 38:
print( ( newline, "This was derived as follows:-", newline ) );
print( ( log OF mw2 ) )
END</
{{out}}
<pre>
Line 58:
More than a light-weight scripting language is really likely to need, but a way of stretching it a bit, and understanding its relationship to other languages. What AppleScript mainly lacks (apart from a well-developed library, and introspective records/dictionaries which know what keys/fields they have), is a coherent type of first class (and potentially anonymous) function. To get first class objects, we have to wrap 2nd class handlers in 1st class scripts.
<
-- How can we compose functions which take simple values as arguments
Line 176:
end call
end script
end sBind</
{{Out}}
Line 189:
=={{header|C++}}==
<
#include <iostream>
#include <string>
Line 232:
cout << result.Log << "\nResult: " << result.Value;
}
</syntaxhighlight>
{{out}}
<pre>
Line 245:
Our monadic Writer elements will be pairs (string . value), where string is the log string.
<
(define (Writer.unit x (log #f))
(if log (cons log x)
Line 288:
add-one → 2
half → 1
</syntaxhighlight>
=={{header|F_Sharp|F#}}==
<
// Monads/Writer monad . Nigel Galloway: July 20th., 2022
type Riter<'n>=Riter of 'n * List<string>
Line 303:
log|>List.iter(printfn "%s")
printfn "Final value = %f" result
</syntaxhighlight>
{{out}}
<pre>
Line 316:
Factor comes with an implementation of Haskell-style monads in the <code>monads</code> vocabulary.
{{works with|Factor|0.99 2019-10-06}}
<
FROM: monads => do ;
Line 324:
[ 1 + "added one, " <writer> ]
[ 2 / "divided by two." <writer> ]
} do .</
{{out}}
<pre>
Line 337:
=={{header|Go}}==
{{trans|Kotlin}}
<
import (
Line 377:
fmt.Println("\nThis was derived as follows:-")
fmt.Println(mw2.log)
}</
{{out}}
Line 395:
Making a logging version of functions (unfortunately, if we use the built-in writer monad we cannot get the values into the logs when binding):
<
import Control.Monad ((>=>))
Line 407:
halfOfAddOneOfRoot = logRoot >=> logAddOne >=> logHalf
main = print $ runWriter (halfOfAddOneOfRoot 5)</
{{Out}}
Line 419:
Based on javascript implementation:
<
incr=: >:
half=: -:
Line 445:
loggingCompose=: dyad define
;(dyad def '<x`:6 loggingBind;y')/x,<loggingUnit y
)</
Task example:
<
1.61803
1{::Lhalf`Lincr`Lroot loggingCompose 5
Line 455:
obtained square root -> 2.23607
added 1 -> 3.23607
divided by 2 -> 1.61803</
=={{header|JavaScript}}==
Line 461:
===ES5===
<
'use strict';
Line 547:
return half_of_addOne_of_root(5);
})();</
{{Out}}
Line 562:
From Javascript ES5 entry.
<
/* writer monad, in Jsish */
Line 664:
divided by 2 -> 1.61803398874989
=!EXPECTEND!=
*/</
{{out}}
Line 671:
=={{header|Julia}}==
<
Base.show(io::IO, w::Writer) = print(io, w.msg, ": ", w.x)
Line 688:
println("$a => $b => $c")
println(bind(f2, "after plus 8", bind(f1, "after times 7", unit(3, "after intialization"))))
</
<pre>
after intialization: 3 => after intialization, after times 7: 21 => after intialization, after times 7, after plus 8: 29
Line 695:
=={{header|Kotlin}}==
<
import kotlin.math.sqrt
Line 725:
println("The Golden Ratio is ${fv.value}")
println("\nThis was derived as follows:-\n${fv.log}")
}</
{{out}}
Line 739:
=={{header|Nim}}==
<
from sugar import `=>`, `->`
Line 758:
echo 5.doneWith.logRoot.logAddOne.logHalf
</syntaxhighlight>
{{out}}
<pre>
Line 766:
=={{header|Perl}}==
{{trans|Raku}}
<
package Writer;
Line 794:
print Unit(5, "Initial value")->Bind(\&root)->Bind(\&addOne)->Bind(\&half)->[1];
</syntaxhighlight>
{{out}}
<pre>
Line 804:
=={{header|Phix}}==
<!--<
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">bind</span><span style="color: #0000FF;">(</span><span style="color: #004080;">object</span> <span style="color: #000000;">m</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">f</span><span style="color: #0000FF;">)</span>
Line 833:
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%f obtained by\n%s"</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">bind</span><span style="color: #0000FF;">(</span><span style="color: #000000;">bind</span><span style="color: #0000FF;">(</span><span style="color: #000000;">bind</span><span style="color: #0000FF;">({</span><span style="color: #000000;">5</span><span style="color: #0000FF;">,</span><span style="color: #008000;">""</span><span style="color: #0000FF;">},</span><span style="color: #000000;">root</span><span style="color: #0000FF;">),</span><span style="color: #000000;">addOne</span><span style="color: #0000FF;">),</span><span style="color: #000000;">half</span><span style="color: #0000FF;">))</span>
<!--</
{{out}}
<pre>
Line 843:
=={{header|PHP}}==
<
/** @var mixed */
Line 886:
print "The Golden Ratio is: {$result->value()}\n";
print join("\n", $result->logs());</
{{out}}
Line 899:
=={{header|Python}}==
<
from __future__ import annotations
Line 956:
print(Writer(5, "initial") >> square_root >> add_one >> half)
</syntaxhighlight>
{{out}}
Line 970:
Basic semantic borrowed from the Monads/List monad entry
{{trans|Go}}
<syntaxhighlight lang="raku"
class Writer { has Numeric $.value ; has Str $.log }
Line 987:
sub half(\v) { Unit v/2, "Divided by two" }
say Unit(5, "Initial value").&Bind(&root).&Bind(&addOne).&Bind(&half).log;</
{{out}}
<pre>Initial value : 5.000000000000
Line 997:
=={{header|Ruby}}==
<
class Writer
attr_reader :value, :log
Line 1,035:
puts "This value was derived as follows:"
puts m2.log
</syntaxhighlight>
{{out}}
Line 1,051:
{{trans|Go}}
{{libheader|Wren-fmt}}
<
class Mwriter {
Line 1,080:
System.print("The Golden Ratio is %(mw2.value)")
System.print("\nThis was derived as follows:-")
System.print(mw2.log)</
{{out}}
Line 1,095:
=={{header|zkl}}==
{{trans|EchoLisp}}
<
fcn init(x){ var X=x, logText=Data(Void," init \U2192; ",x.toString()) }
fcn unit(text) { logText.append(text); self }
Line 1,105:
fcn half{ lift('/(2),"half") }
fcn inc { lift('+(1),"inc") }
}</
<
{{out}}
<pre>
Line 1,115:
half → 1.61803
</pre>
<
Utils.Helpers.fcomp(w.half,w.inc,w.root)(w).println(); // half(inc(root(w)))</
{{out}}
<pre>
Line 1,126:
</pre>
Use bind to add functions to an existing Writer:
<
root,inc,half := w.bind(fcn(x){ x.sqrt() },"root"), w.bind('+(1),"+ 1"), w.bind('/(2),"/ 2");
root(); inc(); half(); w.println();</
{{out}}
<pre>
|