0

所以我有一个使用这个签名的昂贵方法

def func(param: Int): \/[String, Int]

我正在尝试遍历参数列表并返回\/[String, List[Int]],但只要方法返回就停止循环-\/

我想出了这个:

scala> def func(i: Int) = {
     |   if( i > 1 ) { println{"!!"} ;"error".left[Int]}
     |   else i.right[String]
     | }
func: (i: Int)scalaz.\/[String,Int]

scala> val toList = (dis: scalaz.\/[String,Int]) => {dis.map(i => List(i))}
toList: scalaz.\/[String,Int] => scalaz.\/[String,List[Int]] = <function1>

scala> val composed = (func _) andThen toList
composed: Int => scalaz.\/[String,List[Int]] = <function1>

scala> (1 to 3).toList.foldLeftM(List[Int]().right[String]){(dis, i) =>
     |   for{
     |     a <- dis
     |     b <- composed(i)
     |   } yield a |+| b
     | }
<console>:17: error: no type parameters for method foldLeftM: (f: (scalaz.\/[String,List[Int]], Int) => G[scalaz.\/[String,List[Int]]])(implicit M: scalaz.Monad[G])G[scalaz.\/[String,List[Int]]] exist so that it can be applied to arguments ((scalaz.\/[String,List[Int]], Int) => scalaz.\/[String,List[Int]])
 --- because ---
argument expression's type is not compatible with formal parameter type;
 found   : (scalaz.\/[String,List[Int]], Int) => scalaz.\/[String,List[Int]]
 required: (scalaz.\/[String,List[Int]], Int) => ?G[scalaz.\/[String,List[Int]]]

              (1 to 2).toList.foldLeftM(List[Int]().right[String]){(dis, i) =>
                                       ^
<console>:17: error: type mismatch;
 found   : (scalaz.\/[String,List[Int]], Int) => scalaz.\/[String,List[Int]]
 required: (scalaz.\/[String,List[Int]], Int) => G[scalaz.\/[String,List[Int]]]
              (1 to 2).toList.foldLeftM(List[Int]().right[String]){(dis, i) =>
                                                                            ^

这里是什么G[_],正确的结果类型是foldLeftM什么?

4

1 回答 1

0

解决了我犯的两个错误:

  1. 误解了初始/结转值的类型,它应该List[Int]\/
  2. 一个必须显式声明的类型参数foldLeftM

    scala> def func(i: Int) = {
     |   if( i > 1 ) { println{"!!"} ;"error".left[Int]}
     |   else i.right[String]
     | }
    func: (i: Int)scalaz.\/[String,Int]
    
    scala> val toList = (dis: scalaz.\/[String,Int]) => {dis.map(i => List(i))}
    toList: scalaz.\/[String,Int] => scalaz.\/[String,List[Int]] = <function1>
    
    scala> val composed = (func _) andThen toList
    composed: Int => scalaz.\/[String,List[Int]] = <function1>
    
    scala> val f = (dis: List[Int], i: Int) => composed(i).map(r => dis |+| r)
    f: (List[Int], Int) => scalaz.\/[String,List[Int]] = <function2>
    
    scala> (1 to 4).toList.foldLeftM[({type l[a] = String \/ a})#l, List[Int]](List[Int]())(f)
    !!
    res16: scalaz.\/[String,List[Int]] = -\/(error)
    
于 2015-03-20T03:15:46.640 回答