连续传递样式和元素

Continuation-passing style sum elements

我尝试将此代码转换为 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))

一个更简单的方法来做到这一点

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))