Advertisement
Guest User

Untitled

a guest
Apr 9th, 2019
143
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.92 KB | None | 0 0
  1. import cats.data.Reader
  2. import cats.syntax.applicative._
  3.  
  4. case class Db(usernames: Map[Int, String], passwords: Map[String, String])
  5. type DbReader[A] = Reader[Db, A]
  6.  
  7. def findUsername(userId: Int): DbReader[Option[String]] =
  8. Reader(db => db.usernames.get(userId))
  9.  
  10. def checkPassword(username: String, password: String): DbReader[Boolean] =
  11. Reader(db => db.passwords.get(username).contains(password))
  12.  
  13. def checkLogin(userId: Int, password: String): DbReader[Boolean] =
  14. for {
  15. username <- findUsername(userId)
  16. isPasswordOk <- username
  17. .map { username =>
  18. checkPassword(username, password)
  19. }
  20. .getOrElse {
  21. false.pure[DbReader]
  22. }
  23. } yield isPasswordOk
  24.  
  25. val users = Map(1 -> "dade", 2 -> "kate", 3 -> "margo")
  26. val passwords =
  27. Map("dade" -> "zerocool", "kate" -> "acidburn", "margo" -> "secret")
  28. val db = Db(users, passwords)
  29.  
  30. checkLogin(1, "zerocool").run(db)
  31. checkLogin(4, "davinci").run(db)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement