Last active
May 23, 2018 20:19
-
-
Save zsolt-donca/194516909285bd31a43176b0f0cf4469 to your computer and use it in GitHub Desktop.
Part 2: Followup of the FP meetup "Abstractions of higher kind" - using Writer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import cats._ | |
import cats.data._ | |
import cats.implicits._ | |
case class User(age: Int) | |
// notice F: FlatMap; fetchUser returning G[F[User]], and the use of flatTraverse | |
def complicatedFunction[F[_]: Traverse : FlatMap, G[_]: Applicative, A: Monoid](ids: F[Int], fetchUser: Int => G[F[User]], consume: User => A): G[A] = { | |
ids.flatTraverse(fetchUser) | |
.map(_.foldMap(consume)) | |
} | |
type ErrorsAnd[T] = Writer[List[String], T] | |
def fetchUserFromMem(i: Int): ErrorsAnd[List[User]] = { | |
i match { | |
case 1 => Writer(List(), List(User(25))) | |
case 2 => Writer(List(), List(User(25))) | |
case 3 => Writer(List(), List(User(33))) | |
case _ => Writer(List(s"User with id $i not found"), List()) | |
} | |
} | |
val validIds = List(1, 2, 3) | |
val invalidIds = List(21, 22, 1, 2, 3) | |
complicatedFunction(validIds, fetchUserFromMem, u => Map(u.age -> 1)) | |
// ErrorsAnd[scala.collection.immutable.Map[Int,Int]] = WriterT((List(),Map(25 -> 2, 33 -> 1))) | |
complicatedFunction(invalidIds, fetchUserFromMem, u => Map(u.age -> 1)) | |
// ErrorsAnd[scala.collection.immutable.Map[Int,Int]] = WriterT((List(User with id 21 not found, User with id 22 not found),Map(25 -> 2, 33 -> 1))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment