From 989d72857a9b3ec6c3fdad562a141be681c507e2 Mon Sep 17 00:00:00 2001 From: Dave Gurnell Date: Tue, 8 Mar 2016 22:28:07 +0000 Subject: [PATCH] Add .tell and .writer syntax for creating Writers. Fixes #920. --- core/src/main/scala/cats/syntax/all.scala | 1 + core/src/main/scala/cats/syntax/package.scala | 1 + core/src/main/scala/cats/syntax/writer.scala | 13 ++++++++++ .../test/scala/cats/tests/WriterTests.scala | 26 +++++++++++++++++++ 4 files changed, 41 insertions(+) create mode 100644 core/src/main/scala/cats/syntax/writer.scala create mode 100644 tests/src/test/scala/cats/tests/WriterTests.scala diff --git a/core/src/main/scala/cats/syntax/all.scala b/core/src/main/scala/cats/syntax/all.scala index 2a2f68faef..b99ed8785f 100644 --- a/core/src/main/scala/cats/syntax/all.scala +++ b/core/src/main/scala/cats/syntax/all.scala @@ -37,3 +37,4 @@ trait AllSyntax with XorSyntax with ValidatedSyntax with CoproductSyntax + with WriterSyntax diff --git a/core/src/main/scala/cats/syntax/package.scala b/core/src/main/scala/cats/syntax/package.scala index 154a9e94cf..26ec7fd4f5 100644 --- a/core/src/main/scala/cats/syntax/package.scala +++ b/core/src/main/scala/cats/syntax/package.scala @@ -35,4 +35,5 @@ package object syntax { object traverse extends TraverseSyntax object xor extends XorSyntax object validated extends ValidatedSyntax + object writer extends WriterSyntax } diff --git a/core/src/main/scala/cats/syntax/writer.scala b/core/src/main/scala/cats/syntax/writer.scala new file mode 100644 index 0000000000..41dab81a63 --- /dev/null +++ b/core/src/main/scala/cats/syntax/writer.scala @@ -0,0 +1,13 @@ +package cats +package syntax + +import cats.data.Writer + +trait WriterSyntax { + implicit def writerIdSyntax[A](a: A): WriterIdSyntax[A] = new WriterIdSyntax(a) +} + +final class WriterIdSyntax[A](val a: A) extends AnyVal { + def tell: Writer[A, Unit] = Writer(a, ()) + def writer[W](w: W): Writer[W, A] = Writer(w, a) +} diff --git a/tests/src/test/scala/cats/tests/WriterTests.scala b/tests/src/test/scala/cats/tests/WriterTests.scala new file mode 100644 index 0000000000..6b93c1ef72 --- /dev/null +++ b/tests/src/test/scala/cats/tests/WriterTests.scala @@ -0,0 +1,26 @@ +package cats +package tests + +import cats.data.Writer +import cats.laws.discipline.eq._ + +class WriterTests extends CatsSuite { + test("pure syntax creates a writer with an empty log"){ + forAll { (result: String) => + type Logged[A] = Writer[List[Int], A] + result.pure[Logged] should === (Writer(List.empty[Int], result)) + } + } + + test("tell syntax creates a writer with a unit result"){ + forAll { (log: List[Int]) => + log.tell should === (Writer(log, ())) + } + } + + test("writer syntax creates a writer with the specified result and log") { + forAll { (result: String, log: List[Int]) => + result.writer(log) should === (Writer(log, result)) + } + } +}