Guest User

Untitled

a guest
Feb 3rd, 2019
161
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.37 KB | None | 0 0
  1. /**
  2. *
  3. * The classic use of Readers is to build programs that accept a configuration as a
  4. * parameter. Let’s ground this with a complete example of a simple login system.
  5. * Our configuration will consist of two databases: a list of valid users and a
  6. * list of their passwords:
  7. */
  8.  
  9. case class Db(usernames: Map[Int, String],
  10. passwords: Map[String, String]
  11. )
  12.  
  13.  
  14. type DbReader[A] = Reader[Db, A]
  15.  
  16. def findUsername(userId: Int): DbReader[Option[String]] = Reader(_.usernames.get(userId))
  17.  
  18. def checkPassword(username: String,
  19. password: String): DbReader[Boolean] =
  20. Reader(_.passwords.get(username).contains(password))
  21.  
  22. import cats.syntax.applicative._ // for pure
  23.  
  24. def checkLogin(userId: Int,
  25. password: String): DbReader[Boolean] =
  26. for {
  27. maybeUsername <- findUsername(userId)
  28. passwordOk <- maybeUsername match {
  29. case Some(u) => checkPassword(u, password)
  30. case None => false.pure[DbReader]
  31. }
  32. } yield passwordOk
  33.  
  34.  
  35. val users = Map(
  36. 1 -> "dade",
  37. 2 -> "kate",
  38. 3 -> "margo"
  39. )
  40. val passwords = Map(
  41. "dade" -> "zerocool",
  42. "kate" -> "acidburn",
  43. "margo" -> "secret"
  44. )
  45.  
  46. val db = Db(users, passwords)
  47. checkLogin(1, "zerocool").run(db)
  48. // res10: cats.Id[Boolean] = true
  49. checkLogin(4, "davinci").run(db)
  50. // res11: cats.Id[Boolean] = false
Add Comment
Please, Sign In to add comment