如何在scala中订购对象列表(混合鸡尾酒)

时间:2015-06-29 09:50:23

标签: scala

我对Scala中的列表排序感到困惑。

我想说明如何混合列表。例如,我有一个数字列表。这些数字有一封信。我想用字母图案来订购这些数字。

val numbers = List((1, "a"), (2, "b"), (3, "a"), (4, "a"), (5, "b"), (6, "a"), (7, "a"))
// order pattern
val cocktail = List("a", "b", "a", "b") 
// Expected output: 1, 2, 3, 5 

val cocktail2 = List("a", "a", "a", "b") 
// Expected output: 1, 3, 4, 2 

请建议吗?

更新

感谢您的快速回复。一切正在发挥作用!

2 个答案:

答案 0 :(得分:0)

你可以这样做:

def orderWithPattern(list : List[(Int, String)], pattern: List[String]) : List[Int] = {
  val start = (list, List[Int]())
  // fold over the pattern list and try to find the letters in the list
  pattern.foldLeft(start) { case ((list, numbers), elem) => 
    list.indexWhere(_._2 == elem) match {
      case -1 => 
        // letter in pattern not found
        (list, numbers)
      case index =>
        // letter in pattern found
        // => remove from list and add to currently (reversed) ordered numbers
        val (begin, (n, letter) :: end) = list.splitAt(index)
        (begin ::: end, n :: numbers)
     }   
  }._2.reverse // return reversed numbers
}

可以用作:

scala> orderWithPattern(numbers, cocktail)
res14: List[Int] = List(1, 2, 3, 5)

scala> orderWithPattern(numbers, List("a", "a", "c", "d", "b"))
res15: List[Int] = List(1, 3, 2)

答案 1 :(得分:0)

object ListOrdering extends App {

  val numbers = List((1, "a"), (2, "b"), (3, "a"), (4, "a"), (5, "b"), (6, "a"), (7, "a"))
  val cocktail = List("a", "b", "a", "b")
  val cocktail2 = List("a", "a", "a", "b")

  def mix[T, S](order: List[S], ss: List[(T, S)]): List[T] = {
    def loop(acc: List[T], order: List[S], ls: List[(T, S)]): List[T] = order match {
      case Nil => acc
      case x :: xs =>
        val firstFound = ls.find(_._2 == x).get    //this can throw Exception! You must have correct pattern!
        val newLs = ls.filter(_ != firstFound)
        loop(acc :+ firstFound._1, xs, newLs)
    }
    loop(Nil, order, ss)
  }

  println(mix(cocktail, numbers))
  println(mix(cocktail2, numbers))

}

使用类型参数T,S可以概括混合函数以适用于不同类型。你也没有提到在模式不正确的情况下该怎么做,所以这段代码只会抛出NoSuchElementException。