thenewOne1234567890
thenewOne1234567890

Reputation: 33

Continuation-passing style sum elements

i try to transform this code into the CPS form:

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

I ma new to scala and got very big problems undertand the syntax. it would be very helpful if you give me some syntax to solve this task

Here is my code with a typ mismatch:

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

Upvotes: 0

Views: 310

Answers (1)

Mikel San Vicente
Mikel San Vicente

Reputation: 3863

A much more simple approach to do that

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

This can be written in this other way

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

foldLeft method pass the counter in each step for you.

The simplest way to do this is

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

or

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

EDIT: building the computation

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

or

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

Upvotes: 0

Related Questions