gpt4 book ai didi

scala - foreach 中的模式匹配,然后执行最后一步

转载 作者:行者123 更新时间:2023-12-02 03:03:49 30 4
gpt4 key购买 nike

foreach 语句中进行模式匹配后是否可以执行任何操作?
我想做一个匹配后步骤,例如设置一个变量。我还想强制返回一个 Unit,因为我的 foreach 是 String => Unit,并且默认情况下 Scala 希望返回最后一条语句。

这是一些代码:

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

更新:新的代码和上下文。还添加了新问题:)它们嵌入在评论中。

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

最佳答案

我不知道您的 ctm 是什么,但您始终可以这样做:

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

请注意,当您想要使用代码块作为 foreach() 的参数时,应使用 {} 而不是 ()

关于scala - foreach 中的模式匹配,然后执行最后一步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11302979/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com