Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Scala 连续传递式和元素_Scala_Continuation Passing - Fatal编程技术网

Scala 连续传递式和元素

Scala 连续传递式和元素,scala,continuation-passing,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 =

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


这个答案与本练习的目的背道而驰,您应该在整个计算过程中执行连续运算。第一个代码段正是在进行连续运算。您的第一个代码段没有编译,因为
cont
没有在任何地方定义。如果是,它将具有type
Int=>Unit
,因此
cont+i
不会进行类型检查。您只是直接计算总和,然后将其传递给continuation,而不是在整个求和过程中使用它。cont是传递给foldLeft的分部函数的第一个参数,它的类型为Int,将代码复制并粘贴到Scala控制台,您将看到它已编译……关键是
cont
应该是一个表示其余计算的函数。在OP is中,类型为
Int=>Unit
,不能将其更改为
Int
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))