gpt4 book ai didi

scala - 表达相似值对象的惯用 scala/FP 方式

转载 作者:行者123 更新时间:2023-12-02 05:37:06 25 4
gpt4 key购买 nike

我想知道表达类似消息(值对象)的惯用方式是什么假设我有一些想要发送的消息:UserEnter、UserLeft、UserSendGreeting 等。希望以下内容能表达我的困境

我认为有两个选项可以表达它:

trait UserAction
case class UserEnter (username:String,hour:Long,day:WeekDay,room:Int)
case class UserLeft (username:String,hour:Long,day:WeekDay,room:Int)
case class UserSendGreeting (username:String,,hour:Long,day:WeekDay,greeting:String)

def foo(userActions:List[UserAction]) = {
userActions match {
case UserEnter(userName)::tail =>
sendWelcomeMessage(userName)
handleOtherActions(tail)

case UserLeft::tail => "must enter first"
case _ => "do something else"
}

另一种方法是:

    trait Action
case class Enter(room:Int) extends Action
case object Left(room:Int) extends Action
case object Greet(msg:String) extends Action

case class UserAction(username:String,action:Action,,hour:Long,day:WeekDay)

def foo(userActions:List[UserAction]) = {
userActions match {
case head::tail if head.action == Enter =>
sendWelcomeMessage(head.userName)
handleOtherActions(tail)
case head::tail if head.action == Left => "must enter first"
case _ => "do something else"
}

第一个选项更明确,更容易进行模式匹配,但代码重复性更高。另一种对操作本身更明确,但模式匹配更详细
哪种方式更好?

最佳答案

不要让事情过于复杂化。如果您需要一对User(在您的情况下是字符串名称)和Action,请使用Tuple。将所有“...其他属性”收集到相应的 Action 中也是有意义的。

type User = String

sealed trait Action

case class Enter(room:Int) extends Action

case class Left(room:Int) extends Action

case class Greet(msg:String) extends Action


def foo(userActions:List[(User, Action)]) = userActions match {
case (username, _:Enter)::tail =>
sendWelcomeMessage(username)
handleOtherActions(tail)
case (username, _:Left)::tail => "must enter first"
case _ => "do something else"
}

另外不要忘记,模式匹配允许您取消任意深度的层次结构:

case (username, Enter(room))::tail =>

关于scala - 表达相似值对象的惯用 scala/FP 方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35548641/

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