Data update
This commit is contained in:
parent
4d5544505c
commit
4924dd0264
3073 changed files with 55820 additions and 4408 deletions
47
Task/Monads-Writer-monad/Koka/monads-writer-monad.koka
Normal file
47
Task/Monads-Writer-monad/Koka/monads-writer-monad.koka
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
import std/num/float64
|
||||
|
||||
effect log
|
||||
fun log(s: string): ()
|
||||
|
||||
fun write(s: string, f: float64): log float64
|
||||
log(s.pad-right(17) ++ ": " ++ f.show)
|
||||
f
|
||||
|
||||
fun root(d) write("Took square root", sqrt(d))
|
||||
fun half(d) write("Divided by two", d / 2.0)
|
||||
fun add-one(d) write("Added one", d + 1.0)
|
||||
|
||||
fun solution1()
|
||||
var logv := []
|
||||
with handler
|
||||
fun log(s)
|
||||
logv := Cons(s, logv)
|
||||
return(result) (result, logv.reverse)
|
||||
write("Initial value", 5.0).root.add-one.half
|
||||
|
||||
struct writer<v>
|
||||
wlog: list<string>
|
||||
v: v
|
||||
|
||||
fun unit(s, v, ?show)
|
||||
Writer([s.pad-right(17) ++ ": " ++ v.show], v)
|
||||
fun bind(m, f)
|
||||
val Writer(log, v') = f(m.v)
|
||||
Writer(m.wlog ++ log, v')
|
||||
fun root-v2(d) unit("Took square root", sqrt(d))
|
||||
fun half-v2(d) unit("Divided by two", d / 2.0)
|
||||
fun add-one-v2(d) unit("Added one", d + 1.0)
|
||||
fun solution2()
|
||||
unit("Initial value", 5.0).bind(root-v2).bind(add-one-v2).bind(half-v2)
|
||||
|
||||
fun main()
|
||||
val (result, log) = solution1()
|
||||
println("Version 1 (effect handlers):")
|
||||
println("The Golden Ratio is " ++ result.show)
|
||||
println("Derived as follows:")
|
||||
println(log.map(" " ++ _).join("\n"))
|
||||
val Writer(log2, result2) = solution2()
|
||||
println("\nVersion 2 (monad):")
|
||||
println("The Golden Ratio is " ++ result2.show)
|
||||
println("Derived as follows:")
|
||||
println(log2.map(" " ++ _).join("\n"))
|
||||
Loading…
Add table
Add a link
Reference in a new issue