延续传递风格和元素

时间:2017-02-12 17:43:08

标签: scala continuation-passing

我尝试将此代码转换为CPS格式:

   def sum ( lst :  List [ Int ]) :  Int  =  lst match {
     case Nil => 0
     case first :: rest => first  +  sum ( rest )
   }


  def sumC1(lst :  List [ Int ], k :  Int => Unit ) :  Unit  =  lst match {
     case lst => k(sum(lst))
   }

我是scala的新手,并且在语法方面遇到了很大的问题。如果你给我一些语法来解决这个任务会非常有用

这是我的代码与典型不匹配:

  def sum(lst: List[Int])(cont: Int => Int): Int = lst match {
    case Nil => cont(0)
    case first :: rest => sum(lst){rest => cont(first + rest) }
  }

  def sumC1(lst: List[Int], k: Int => Unit): Unit = lst match {
    case lst => k(sum(lst))
  }
  sumC1(List(1, 2, 3), (v: Int) => println(v))

1 个答案:

答案 0 :(得分:0)

更简单的方法

def sum(lst: List[Int]): Int =
    lst.foldLeft(0){
      case(cont, i) => cont +i
    }
def sumC1(lst: List[Int], k: Int => Unit): Unit = 
    k(sum(lst))

这可以用其他方式编写

def sum(lst: List[Int]): Int =
    lst.foldLeft(0)(_ + _)
def sumC1(lst: List[Int], k: Int => Unit): Unit = 
    k(sum(lst))

foldLeft方法为您在每个步骤中传递计数器。

最简单的方法是

def sumC1(lst: List[Int], k: Int => Unit): Unit = 
    k(lst.sum)

def sum(lst: List[Int]): Int =
    lst.fold(0)(_ + _)
def sumC1(lst: List[Int], k: Int => Unit): Unit = 
    k(sum(lst))

修改: 建立计算

def sum(lst: List[Int]): Int =
    lst.foldLeft[ Int => Int](v => v){
      case(cont, i) =>  v => v + cont(i)
    }(0)

def sumC1(lst: List[Int], k: Int => Unit): Unit =
    k(sum(lst))

def sum(lst: List[Int]): Int =
    lst.foldLeft[ Unit => Int](Unit => 0){
      case(cont, i) =>  Unit => i + cont()
    }()

def sumC1(lst: List[Int], k: Int => Unit): Unit =
    k(sum(lst))