是否有像 sortWith 函数一样工作的本机分组函数? [英] Is there a native grouping function that works like the sortWith function?

查看:37
本文介绍了是否有像 sortWith 函数一样工作的本机分组函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一些库(例如 Spark 和其他 Scala 扩展)具有可用的groupWith"功能.此函数允许您将一个元素与集合的其余部分进行比较,然后使用一个或多个谓词对其进行分组.Scala 中似乎没有为此提供任何本机功能,但它们确实具有 sortWith 功能,其行为类似但仅对项目进行排序而不是对它们进行分组.如果解释不够,这里有一个小代码示例,它应该显示我正在尝试做的事情:

There are a few libraries such as Spark and other Scala extensions that have the "groupWith" function available. This function allows you to compare an element to the rest of the collection and then group it using one or more predicates. There doesn't seem to be any native functionality in Scala for this but they do have the sortWith function that behaves similarly but only sorts the items instead of grouping them. If the explanation isn't sufficient here's a small code sample that should display what I'm trying to do:

val list = List(1,2,3,4,5,5)
val groupedList = list.groupWith{ (e,c) =>
    e == c
}

这是一个非常简单的例子,我想做更复杂的比较,比如

This is a very simple example and I want to do more complicated comparisons such as

e + 1 == c

那么问题又来了,是否有任何原生 Scala 函数可以做到这一点?有什么建议或解决方法吗?

So again the question is are there any native Scala functions that do this? Any suggestions or workarounds?

更新:从给出的简单示例看来,我想要做什么还不是很清楚,这是一个更好的示例:假设我有一个案例类和这些对象的列表:

Update: From the simple examples given it seems it's not exactly clear what I'm trying to do, here's a better example: Say I have a case class and a list of these objects:

case class Item(num: Int, color: String)
val list = List(new Item(13, "red"), new Item(14,"red"), new Item(15, "blue"), new Item(16, "red"))

list.groupWith{ (e,c) =>
    (e.num -1 == c.num || e.num + 1 == c.num ) && e.color == c.color        
}

这应该返回如下内容:

res8: List[List[Item]] = List(List(Item(13,red), Item(14,red)), List(Item(15,blue)), List(Item(16,red)))

推荐答案

这是一个实现:

// Takes the list as a parameter, can use pimp-my-library if you want
def groupWith[A](xs: List[A], f: (A, A) => Boolean) = {
  // helper function to add "e" to any list with a member that matches the predicate
  // otherwise add it to a list of its own
  def addtoGroup(gs: List[List[A]], e: A): List[List[A]] = {
    val (before, after) = gs.span(_.exists(!f(_, e)))
    if (after.isEmpty)
      List(e) :: gs
    else
      before ::: (e :: after.head) :: after.tail
  }
  // now a simple foldLeft adding each element to the appropriate list
  xs.foldLeft(Nil: List[List[A]])(addtoGroup)
} 

groupWith(list, { (e: Item, c: Item) =>
                    (e.num - 1 == c.num || e.num + 1 == c.num) && e.color == c.color})

//| res0: List[List[groups.groups.Item]] =
//         List(List(Item(16,red)),
//              List(Item(15 ,blue)), 
//              List(Item(14,red), Item(13,red)))

这篇关于是否有像 sortWith 函数一样工作的本机分组函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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