2015-03-19 47 views
0

所以,我有一个昂贵的方法与此签名短路的函数列表返回/

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

我试图环比则params的列表并返回\/[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正确的结果类型?

回答

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)