如何改善这个功能? [英] How to improve this function?

查看:68
本文介绍了如何改善这个功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个这样的数据结构:

Suppose I've got a data structure like that:

case class B(bx: Int)
case class A(ax: Int, bs: Seq[B])

我正在编写一个函数 A => Seq [(Int,Option [Int])] 如下:

I am writing a function A => Seq[(Int, Option[Int])] as follows:

def foo(a: A): Seq[(Int, Option[Int])] = 
  if (a.bs.isEmpty) Seq((a.ax, None)) else a.bs.map(b => (a.ax, Some(b.bx)))

这似乎可行,但我不喜欢分枝。您将如何改善 foo

It seems working but I don't like the branching. How would you improve foo ?

推荐答案

另一种方法-添加辅助函数使用 Seq [T] 并返回 Seq [Option [T]] 的函数,其中输出为从不为空-如果输入为空,则输出结果中将只有一个 None 元素:

Another option - add an auxiliary function that takes a Seq[T] and returns a Seq[Option[T]] where the output is never empty - if the input is empty, the output would have a single None element in its result:

def foo(a: A): Seq[(Int, Option[Int])] = toOptions(a.bs.map(_.bx)).map((a.ax, _))

// always returns a non-empty list - with None as the only value for empty input
def toOptions[T](s: Seq[T]): Seq[Option[T]] = s.headOption +: s.drop(1).map(Some(_))

优点:


  • 真正没有分支(包括 getOrElse 这是一种分支,尽管它更优雅)

  • 不重复构建元组( a.ax 叫过一次)

  • 关注点分离得很好(构建一个永不空的列表与处理wi A和Bs)

  • This truly has no branching (including getOrElse which is a kind of branching, albeit a more elegant one)
  • No repetition of building the tuple (a.ax called once)
  • Nice separation of concerns (building a never-empty list vs. dealing with A and Bs)

这篇关于如何改善这个功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆