Skip to content

Instantly share code, notes, and snippets.

@mossprescott
Last active August 29, 2015 14:04
Show Gist options
  • Select an option

  • Save mossprescott/f6a088d403d31bd21215 to your computer and use it in GitHub Desktop.

Select an option

Save mossprescott/f6a088d403d31bd21215 to your computer and use it in GitHub Desktop.
WriterT examples
// See http://stackoverflow.com/a/11951799
// Just Writer:
def calc1a: Writer[List[String], Int] = Writer("doing calc" :: Nil, 11)
def calc1b: Writer[List[String], Int] = Writer("other calc" :: Nil, 22)
val r1 = for {
a <- calc1a
b <- calc1b
} yield a + b
println(r1.run)
// (List(doing calc, other calc),33)
// Writer inside Option:
def calc2a: WriterT[Option, List[String], Int] = WriterT((("doing calc" :: Nil) -> 11).point[Option])
def calc2b: WriterT[Option, List[String], Int] = WriterT((("other calc" :: Nil) -> 22).point[Option])
  //def calc2a: WriterT[Option, List[String], Int] = WriterT(Some((("doing calc" :: Nil) -> 11)))
  //def calc2b: WriterT[Option, List[String], Int] = WriterT(None: Option[(List[String], Int)])
val r2 = for {
a <- calc2a
b <- calc2b
} yield a + b
println(r2.run)
// Some((List(doing calc, other calc),33))
// Writer outside Option:
type Logger[A] = Writer[List[String], A] // source had Logger[+A]
def calc3a = OptionT[Logger, Int](Writer("doing calc" :: Nil, Some(11)))
def calc3b = OptionT[Logger, Int](Writer("other calc" :: Nil, None))
val r3 = for {
a <- calc3a
b <- calc3b
} yield a + b
println(r3.run.run)
// (List(doing calc, other calc),None)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment