scala - Is the Writer Monad effectively the same as the State Monad? -
there's great tutorial here seems suggest me writer monad special case tuple object operations on behalf of (a,b). writer accumulates values on left (which a) , has corresponding monoid (hence can accumulate or mutate state). if collection, accumulates.
the state monad object deals internal tuple. both can flatmap'd, map'd, etc. , operations seem same me. how different? (please respond scala example, i'm not familiar haskel). thanks!
your intuition these 2 monads closely related right. difference writer
more limited, in doesn't allow read accumulated state (until cash out @ end). thing can state in writer
tack more stuff onto end.
more concisely, state[s, a]
kind of wrapper s => (s, a)
, while writer[w, a]
wrapper (w, a)
.
consider following usage of writer
:
import scalaz._, scalaz._ def addw(x: int, y: int): writer[list[string], int] = writer(list(s"$x + $y"), x + y) val w = { <- addw(1, 2) b <- addw(3, 4) c <- addw(a, b) } yield c
now can run computation:
scala> val (log, res) = w.run log: list[string] = list(1 + 2, 3 + 4, 3 + 7) res: int = 10
we same thing state
:
def adds(x: int, y: int) = state((log: list[string]) => (log |+| list(s"$x + $y"), x + y)) val s = { <- adds(1, 2) b <- adds(3, 4) c <- adds(a, b) } yield c
and then:
scala> val (log, res) = s.run(nil) log: list[string] = list(1 + 2, 3 + 4, 3 + 7) res: int = 10
but little more verbose, , lots of other things state
couldn't writer
.
so moral of story should use writer
whenever can—your solution cleaner, more concise, , you'll satisfaction of having used appropriate abstraction.
very writer
won't give power need, though, , in cases state
waiting you.
Comments
Post a Comment