Monads/Writer monad: Difference between revisions
Content added Content deleted
(Realize in F#) |
|||
Line 290: | Line 290: | ||
</lang> |
</lang> |
||
=={{header|F_Sharp|F#}}== |
|||
<lang fsharp> |
|||
// Monads/Writer monad . Nigel Galloway: July 20th., 2022 |
|||
type Riter<'n,'g>=Riter of 'n * List<'g> |
|||
let bind=function |(n,g)->Riter(n,[g]) |
|||
let eval=function |Riter(n,g)->(n,g) |
|||
let compose f=function |Riter(n,g)->let n,l=eval(f n) in Riter(n,List.append g l) |
|||
let initV(n:float)=bind(n,sprintf "Initial Value %f" n) |
|||
let sqrt n=bind(sqrt n,"Took square root") |
|||
let div2 n=bind(n/2.0,"Divided by 2") |
|||
let incr n=bind(n+1.0,"Added 1") |
|||
let result,log=eval(initV 5.0|>compose sqrt|>compose incr|>compose div2) |
|||
log|>List.iter(printfn "%s") |
|||
printfn "Final value = %f" result |
|||
</lang> |
|||
{{out}} |
|||
<pre> |
|||
Initial Value 5.000000 |
|||
Took square root |
|||
Added 1 |
|||
Divided by 2 |
|||
Final value = 1.618034 |
|||
</pre> |
|||
=={{header|Factor}}== |
=={{header|Factor}}== |
||
Factor comes with an implementation of Haskell-style monads in the <code>monads</code> vocabulary. |
Factor comes with an implementation of Haskell-style monads in the <code>monads</code> vocabulary. |