简体   繁体   English

Scala中更好的函数输入/输出参数样式

[英]Better functional in/out arguments style in Scala

This code works fine so far but i don't like the tuples everywhere like this which leads to using _.1 and _2 etc which is less expressive. 到目前为止,这段代码可以正常工作,但是我不喜欢到处都是这样的元组,这会导致使用_.1和_2等表现力较低的代码。 I can implement wrapper classes that which have more expressive names. 我可以实现包装类,这些包装类具有更具表现力的名称。 Is there a better approach? 有没有更好的方法?

trait DrawingSteps {

  def prompt(savedCommands: List[Command]): IO[(List[Command], Unit)]
  def read(savedCommands: List[Command]): IO[(List[Command], String)]
  def parseAndAppend(in: (List[Command], String)): List[Command]
  def invoke(savedCommands: List[Command]): IO[(List[Command], Unit)]

  def drawingProgram(savedCommands:List[Command] = List()):IO[(List[Command],Unit)] = for {
    t <- prompt(savedCommands)
    rawCommand <- read(t._1)
    commands = parseAndAppend(rawCommand)
    output <- invoke(commands)
  } yield output._1  match {
    case (_:CommandIsQuit)::_  => FP.exit(output._1).run
    case _ => drawingProgram(output._1).run
  }
}

You can always use pattern matching to deconstruct case classes/tuples and give meaningful names instead of using tuple elements ( _1 ). 您始终可以使用模式匹配来解构案例类/元组并给出有意义的名称,而不是使用元组元素( _1 )。 Here is an example: 这是一个例子:

trait DrawingSteps {

  def prompt(savedCommands: List[Command]): IO[(List[Command], Unit)]
  def read(savedCommands: List[Command]): IO[(List[Command], String)]
  def parseAndAppend(in: (List[Command], String)): List[Command]
  def invoke(savedCommands: List[Command]): IO[(List[Command], Unit)]

  def drawingProgram(savedCommands:List[Command] = List()):IO[(List[Command],Unit)] = for {
    (inCmd, _) <- prompt(savedCommands)
    rawCommand <- read(inCmd)
    commands = parseAndAppend(rawCommand)
    (outCmd, _) <- invoke(commands)
  } yield outCmd match {
    case (_:CommandIsQuit)::_  => FP.exit(outCmd).run
    case _ => drawingProgram(outCmd).run
  }
}

I guess you could replace tuples with HLists if you find yourself having lots of tuples with arity greater than 2. Looking at your code you have lots of repetitive return types like IO[(List[Command], Unit)] which can be declared with type alias or could benefit from being refactored into a case class for even better naming. 我猜如果您发现自己有很多元数大于2的元组,则可以用HLists替换元组。在您的代码中,您有很多重复的返回类型,如IO[(List[Command], Unit)] ,可以用类型别名,或者可以受益于重构为case类以获得更好的命名。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM