我正在学习学习黄曲柳和给你一个更好的哈斯克尔,并想知道如何将filterM示例从LYAHFGG转换到Scala。
fst $ runWriter $ filterM keepSmall [9,1,5,2,10,3]
将keepSmall定义为
keepSmall :: Int -> Writer [String] Bool
keepSmall x
| x < 4 = do
tell ["Keeping " ++ show x]
return True
| otherwise = do
tell [show x ++ " is too large, throwing it away"]
return False我天真的方法以编译错误结束,我不知道如何解决这个问题!
val keepSmall: (Int => WriterT[Id, Vector[String], Boolean]) = (x: Int) =>
if (x < 4) for {
_ <- Vector("Keeping " + x.shows).tell
} yield true
else for {
_ <- Vector(x.shows + " is too large, throwing it away").tell
} yield false
println(List(9,1,5,2,10,3) filterM keepSmall)编译错误:
Error:(182, 32) no type parameters for method filterM: (p: Int => M[Boolean])(implicit evidence$4: scalaz.Applicative[M])M[List[Int]] exist so that it can be applied to arguments (Int => scalaz.WriterT[scalaz.Scalaz.Id,Vector[String],Boolean])
--- because ---
argument expression's type is not compatible with formal parameter type;
found : Int => scalaz.WriterT[scalaz.Scalaz.Id,Vector[String],Boolean]
required: Int => ?M[Boolean]
println(List(9,1,5,2,10,3) filterM keepSmall)
^和
Error:(182, 40) type mismatch;
found : Int => scalaz.WriterT[scalaz.Scalaz.Id,Vector[String],Boolean]
required: Int => M[Boolean]
println(List(9,1,5,2,10,3) filterM keepSmall)
^发布于 2015-09-21 10:39:58
这个问题是因为Scala不能真正知道如何在filterM所期望的参数中加入一个有三个洞的类型,这个参数只有一个填充了Boolean的洞。
您可以使用这样的奇怪类型-lambda语法来解决您的问题(没有测试,可能不起作用):
val keepSmall: (Int => ({type L[T] = WriterT[Id, Vector[String], T]})#L) = ...或者(更容易)引入一个类型别名,如下所示:
type MyWriter[T] = WriterT[Id, Vector[String], T]
val keepSmall: (Int => MyWriter[Boolean]) = ...这将确保filterM所期望的参数类型与所提供的参数类型相匹配。
https://stackoverflow.com/questions/32692819
复制相似问题