Is there a native grouping function that works like the sortWith function?

后端 未结 2 929
独厮守ぢ
独厮守ぢ 2020-12-21 20:45

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

2条回答
  •  别那么骄傲
    2020-12-21 21:45

    Here's an implementation:

    // 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)))
    

提交回复
热议问题