Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pattern match in foreach and then do a final step

Is it possible to do anything after a pattern match in a foreach statement?
I want to do a post match step e.g. to set a variable. I also want to force a Unit return as my foreach is String => Unit, and by default Scala wants to return the last statement.

Here is some code:

    Iteratee.foreach[String](_ match {
      case "date" => out.push("Current date: " + new Date().toString + "<br/>")
      case "since" => out.push("Last command executed: " + (ctm - last) + "ms before now<br/>")
      case unknow => out.push("Command: " + unknown + " not recognized <br/>")
    } // here I would like to set "last = ctm" (will be a Long) 
    ) 

UPDATED: New code and context. Also new questions added :) They are embedded in the comments.

def socket = WebSocket.using[String] { request =>

 // Comment from an answer bellow but what are the side effects?
 // By convention, methods with side effects takes an empty argument list
 def ctm(): Long = System.currentTimeMillis

 var last: Long = ctm

 // Command handlers
 // Comment from an answer bellow but what are the side effects?
 // By convention, methods with side effects takes an empty argument list
 def date() = "Current date: " + new Date().toString + "<br/>"
 def since(last: Long) = "Last command executed: " + (ctm - last) + "ms before now<br/>"
 def unknown(cmd: String) = "Command: " + cmd + " not recognized <br/>"

 val out = Enumerator.imperative[String] {}

 // How to transform into the mapping strategy given in lpaul7's nice answer.
 lazy val in = Iteratee.foreach[String](_ match {
   case "date" => out.push(date)
   case "since" => out.push(since(last))
   case unknown => out.push(unknown)
 } // Here I want to update the variable last to "last = ctm"
 ).mapDone { _ =>
   println("Disconnected")
 }

 (in, out)
}
like image 802
Farmor Avatar asked Jul 03 '12 00:07

Farmor


1 Answers

I don't know what your ctm is, but you could always do this:

val xs = List("date", "since", "other1", "other2")

xs.foreach { str =>

    str match {
        case "date"  => println("Match Date")
        case "since" => println("Match Since")
        case unknow  => println("Others")
    } 

    println("Put your post step here")
}

Note you should use {} instead of () when you want use a block of code as the argument of foreach().

like image 99
Brian Hsu Avatar answered Sep 25 '22 13:09

Brian Hsu