我尝试第一次实现读者monad。
我想使用monadic样式来查询数据库。
用例1:用户与同事有一对一的关系。伪代码是getUserById(getUserById(id).getColleague())
用例2:按ID检索用户列表。伪代码是List(getUserById(id1), getUserById(id2))
这似乎是monad的好用例。我的目标是看看我是否可以利用monads来改进我的代码
PS:请提供至少一个没有scalaz的答案。
以下是代码:
package monad
import com.mongodb.casbah.Imports._
object Monad {
type UserId = Int
case class User(id: UserId, name: String, colleagueId: UserId)
trait Reader[I, A] { self =>
def run(id: I) : A
def map[B](f: A => B) : Reader[I, B] =
new Reader[I, B] { def run(id: I) = f(self.run(id)) }
def flatMap[B](f: A => Reader[I, B]) : Reader[I, B] =
new Reader[I, B] { def run(id: I) = f(self.run(id)).run(id) }
}
def coll = MongoClient()("test")("user")
def DBObject2User(o: DBObject) : User = User(o.as[Double]("id").toInt, o.as[String]("name"), o.as[Double]("colleague").toInt)
// Strange design, id is not used…
def User2Colleague(u: User) : Reader[UserId, DBObject] =
unit(coll.findOne(MongoDBObject("id" -> u.colleagueId)).get)
def GetUserById : Reader[UserId, DBObject] =
Reader { id: UserId => coll.findOne(MongoDBObject("id" -> id)).get }
def GetUserById2 : Reader[UserId, User] = GetUserById.map(DBObject2User)
def unit[A](a: => A) = Reader { id: UserId => a }
object Reader {
def apply[I, A](f: I => A) = new Reader[I, A] { def run(i: I) = f(i) }
}
def main(args: Array[String]) {
// I can do
println(GetUserById2.run(1))
// Same with for comprehension
val userReader = for (io <- GetUserById2) yield io
println(userReader.run(1))
//Combination to explore one-to-one relation
val user = GetUserById2.run(1)
val colleague = GetUserById2.run(user.colleagueId)
// Same with flatMap
println(GetUserById2.flatMap(User2Colleague).run(1))
// Same with for-comprehension but doesn't work
val io = for {io <- GetUserById2
io2 <- User2Colleague(io).map(DBObject2User)} yield io2
println(io.run(1))
//TODO: List[Reader] to Reader[List]
}
}
这是好方法吗?我有一些疑问,请参阅我的评论Strange design
我怎样才能改进我的代码?
答案 0 :(得分:3)
我试图重新设计您的提案,使收藏品成为读者的输入,并在我去的时候重新命名。
package monad
package object reader{
type UserId = Int
}
package reader {
case class User(id: UserId, name: String, colleagueId: UserId)
import com.mongodb.casbah.Imports._
import com.mongodb.casbah
trait Reader[I, A] {
self =>
val run = apply _
def apply(id:I):A
def map[B](f: A => B): Reader[I, B] =
new Reader[I, B] {
def apply(id: I) = f(self.run(id))
}
def flatMap[B](f: A => Reader[I, B]): Reader[I, B] =
new Reader[I, B] {
def apply(id: I) = f(self(id)).run(id)
}
}
object Reader {
def unit[A](a: => A) = apply {
id: UserId => a
}
def apply[I, A](f: I => A) = new Reader[I, A] {
def apply(i: I) = f(i)
}
}
object Users {
def asUser(o: DBObject): User = User(o.as[Double]("id").toInt, o.as[String]("name"), o.as[Double]("colleague").toInt)
def colleague(u: User): Reader[MongoCollection, User] =
Reader{
coll => asUser(coll.findOne(MongoDBObject("id" -> u.colleagueId)).get)
}
def getUserById(id:UserId): Reader[MongoCollection, User] =
Reader {
coll => asUser(coll.findOne(MongoDBObject("id" -> id)).get)
}
}
object Client extends App {
import Users._
def coll: casbah.MongoCollection = MongoClient()("test")("user")
// I can do
println(getUserById(1)(coll))
// Same with for comprehension
val userReader = for (user <- getUserById(1)) yield user
println(userReader(coll))
//Combination to explore one-to-one relation
val user = getUserById(1)(coll)
val otherUser = getUserById(user.colleagueId)(coll)
// Same with flatMap
println(getUserById(1).flatMap(colleague)(coll))
// Same with for-comprehension but doesn't work
val coworkerReader = for {user <- getUserById(1)
coworker <- colleague(user)} yield coworker
println(coworkerReader(coll))
}
}
使用这种方法我认为代码更容易测试,因为您可以传递依赖项(MongoCollection),同时只操作签名中的值和函数。阅读更多http://blog.originate.com/blog/2013/10/21/reader-monad-for-dependency-injection/(我不是作者,但这是一个明确的解释)
答案 1 :(得分:3)
答案 2 :(得分:2)
您的用法并不是那么糟糕,我觉得令人困惑的是,通常认为读者的配置输入(如数据库连接数据)通常被认为是被检查用户的ID。
首先我将IO[I,A]
名称更改为Reader[I,A]
只是为了使用这个操作的众所周知的名称[*]
对于User2Colleague(u: User) : IO[UserId, DBObject]
方法,丢弃读取器输入以提供包含在monad中的常量值并不罕见:这正是您的unit
方法所做的!
事实上,我将其改为
def User2Colleague(u: User) : Reader[UserId, DBObject] =
unit(coll.findOne(MongoDBObject("id" -> u.colleagueId)).get)
或甚至更符合您的客户端代码使用
def User2Colleague(u: User): DBObject = coll.findOne(MongoDBObject("id" -> u.colleagueId)).get
...
def main(args: Array[String]) {
val mng = new Mongo()
val io = for {
io <- mng
io2 <- unit(DBObject2User(io))
io3 <- unit(User2Colleague(io2))
} yield (DBObject2User(io3))
println(io.run(1))
我建议尽可能将代码编写为 pure (即没有monadic效果),除非需要。这意味着在常规函数中进行映射,然后根据需要使用unit
进行换行(以便在for comprehension中进行合成类型检查)
[*]通常的IO monad没有输入类型,它只有一个输出类型,通常用于做用户I / O(控制台,打印,发送电子邮件,发送火箭等),即任何有侧面的东西程序本身外部的效果。