我只是在学习 Scala 的同时开始了我的 FP 之旅。
现在需要List[String]
在未过滤的 Web 应用程序中维护一个。当POST
请求发送到端点时,应该从文件更新列表。当 GET 请求发送到同一端点时,将使用该列表。
现在,我试图避免使用var
来保存列表。我知道有时我们必须使用 var 但只是好奇是否有一种优雅的方式来处理这种情况。我试过使用 scalaz.State Iterator 和 Steam。但是因为我不知道如何将当前的不可变状态传递给下一个请求而被卡住了。请问有什么建议吗?
def update = State( l => {
retrieve(filepath) match {
case Success(lines) => (lines.split("[,\n\r]").toVector.map (_.trim), true)
case Failure(_) => {
log.error(s"Cannot retrieve the file.")
(l, false)
}
}
})
def isContained(message: String) = State(l => (l, l.exists(message.contains)))
/* assume the following get or post method will be invoked when GET or POST request is sent to the endpoint */
def post() = update(Vector.empty) // how can I pass the updated state to the get method
def get(msg: String): Boolean = isContained(msg)(???)._2
然后我不知道如何将当前状态作为输入传递给下一次访问而不使用var
.