Monads/Writer monad: Difference between revisions

m
syntax highlighting fixup automation
m (syntax highlighting fixup automation)
Line 13:
=={{header|ALGOL 68}}==
{{Trans|Go}}
<langsyntaxhighlight lang="algol68">BEGIN
MODE MWRITER = STRUCT( LONG REAL value
, STRING log
Line 38:
print( ( newline, "This was derived as follows:-", newline ) );
print( ( log OF mw2 ) )
END</langsyntaxhighlight>
{{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.
 
<langsyntaxhighlight AppleScriptlang="applescript">-- WRITER MONAD FOR APPLESCRIPT
 
-- How can we compose functions which take simple values as arguments
Line 176:
end call
end script
end sBind</langsyntaxhighlight>
 
{{Out}}
Line 189:
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <cmath>
#include <iostream>
#include <string>
Line 232:
cout << result.Log << "\nResult: " << result.Value;
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 245:
Our monadic Writer elements will be pairs (string . value), where string is the log string.
 
<langsyntaxhighlight lang="scheme">
(define (Writer.unit x (log #f))
(if log (cons log x)
Line 288:
add-one → 2
half → 1
</syntaxhighlight>
</lang>
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">
// 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>
</lang>
{{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}}
<langsyntaxhighlight lang="factor">USING: kernel math math.functions monads prettyprint ;
FROM: monads => do ;
 
Line 324:
[ 1 + "added one, " <writer> ]
[ 2 / "divided by two." <writer> ]
} do .</langsyntaxhighlight>
{{out}}
<pre>
Line 337:
=={{header|Go}}==
{{trans|Kotlin}}
<langsyntaxhighlight lang="go">package main
 
import (
Line 377:
fmt.Println("\nThis was derived as follows:-")
fmt.Println(mw2.log)
}</langsyntaxhighlight>
 
{{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):
<langsyntaxhighlight lang="haskell">import Control.Monad.Trans.Writer
import Control.Monad ((>=>))
 
Line 407:
halfOfAddOneOfRoot = logRoot >=> logAddOne >=> logHalf
 
main = print $ runWriter (halfOfAddOneOfRoot 5)</langsyntaxhighlight>
 
{{Out}}
Line 419:
Based on javascript implementation:
 
<langsyntaxhighlight Jlang="j">root=: %:
incr=: >:
half=: -:
Line 445:
loggingCompose=: dyad define
;(dyad def '<x`:6 loggingBind;y')/x,<loggingUnit y
)</langsyntaxhighlight>
 
Task example:
 
<langsyntaxhighlight Jlang="j"> 0{::Lhalf`Lincr`Lroot loggingCompose 5
1.61803
1{::Lhalf`Lincr`Lroot loggingCompose 5
Line 455:
obtained square root -> 2.23607
added 1 -> 3.23607
divided by 2 -> 1.61803</langsyntaxhighlight>
 
=={{header|JavaScript}}==
Line 461:
===ES5===
 
<langsyntaxhighlight JavaScriptlang="javascript">(function () {
'use strict';
 
Line 547:
 
return half_of_addOne_of_root(5);
})();</langsyntaxhighlight>
 
{{Out}}
Line 562:
From Javascript ES5 entry.
 
<langsyntaxhighlight lang="javascript">'use strict';
 
/* writer monad, in Jsish */
Line 664:
divided by 2 -> 1.61803398874989
=!EXPECTEND!=
*/</langsyntaxhighlight>
 
{{out}}
Line 671:
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia">struct Writer x::Real; msg::String; end
 
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"))))
</langsyntaxhighlight>{{out}}
<pre>
after intialization: 3 => after intialization, after times 7: 21 => after intialization, after times 7, after plus 8: 29
Line 695:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.2.10
 
import kotlin.math.sqrt
Line 725:
println("The Golden Ratio is ${fv.value}")
println("\nThis was derived as follows:-\n${fv.log}")
}</langsyntaxhighlight>
 
{{out}}
Line 739:
 
=={{header|Nim}}==
<langsyntaxhighlight Nimlang="nim">from math import sqrt
from sugar import `=>`, `->`
 
Line 758:
 
echo 5.doneWith.logRoot.logAddOne.logHalf
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 766:
=={{header|Perl}}==
{{trans|Raku}}
<langsyntaxhighlight Perllang="perl"># 20200704 added Perl programming solution
 
package Writer;
Line 794:
 
print Unit(5, "Initial value")->Bind(\&root)->Bind(\&addOne)->Bind(\&half)->[1];
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 804:
 
=={{header|Phix}}==
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<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>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 843:
 
=={{header|PHP}}==
<langsyntaxhighlight lang="php">class WriterMonad {
 
/** @var mixed */
Line 886:
 
print "The Golden Ratio is: {$result->value()}\n";
print join("\n", $result->logs());</langsyntaxhighlight>
 
{{out}}
Line 899:
=={{header|Python}}==
 
<langsyntaxhighlight lang="python">"""A Writer Monad. Requires Python >= 3.7 for type hints."""
from __future__ import annotations
 
Line 956:
 
print(Writer(5, "initial") >> square_root >> add_one >> half)
</syntaxhighlight>
</lang>
 
{{out}}
Line 970:
Basic semantic borrowed from the Monads/List monad entry
{{trans|Go}}
<syntaxhighlight lang="raku" perl6line># 20200508 Raku programming solution
 
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;</langsyntaxhighlight>
{{out}}
<pre>Initial value : 5.000000000000
Line 997:
=={{header|Ruby}}==
 
<langsyntaxhighlight lang="ruby"># 20220720 Ruby programming solution
class Writer
attr_reader :value, :log
Line 1,035:
puts "This value was derived as follows:"
puts m2.log
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,051:
{{trans|Go}}
{{libheader|Wren-fmt}}
<langsyntaxhighlight lang="ecmascript">import "/fmt" for 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)</langsyntaxhighlight>
 
{{out}}
Line 1,095:
=={{header|zkl}}==
{{trans|EchoLisp}}
<langsyntaxhighlight lang="zkl">class Writer{
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") }
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">Writer(5.0).root().inc().half().println();</langsyntaxhighlight>
{{out}}
<pre>
Line 1,115:
half → 1.61803
</pre>
<langsyntaxhighlight lang="zkl">w:=Writer(5.0);
Utils.Helpers.fcomp(w.half,w.inc,w.root)(w).println(); // half(inc(root(w)))</langsyntaxhighlight>
{{out}}
<pre>
Line 1,126:
</pre>
Use bind to add functions to an existing Writer:
<langsyntaxhighlight 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();</langsyntaxhighlight>
{{out}}
<pre>
10,327

edits