代码之家  ›  专栏  ›  技术社区  ›  rohitmohta

Scala:使用cons方法将元素追加到列表

  •  0
  • rohitmohta  · 技术社区  · 8 年前

    Programming in Scala, 3rd Edition

    类列表确实提供了一个“append”操作,它写的是:+但是这个 操作很少使用,因为附加到 ●需要持续的时间。

    如果您想通过添加元素来高效地构建一个列表,您可以 预先做好准备,完成后再打反向电话。

    // Scala Recommended way - but reverse twice?
    val alist = List("A", "B")
    // cons is O(1)
    // This will print (A, B, C)
    println(("C" :: alist.reverse).reverse)
    
    // Scala also Recommended: Use ListBuffer
    val alb = ListBuffer("A", "B")
    alb.append("C")
    val clist2 = alb.toList
    // This will print (A, B, C)
    println(clist2)
    
    // DO NOT do this, its O(n)
    
    val clist3 = alist :+ "C"
    // This will print (A, B, C)
    println(clist3)
    

    P、 S:我这里指的不是代码优化。一般推荐哪一种,不会收到 重量

    0 回复  |  直到 8 年前
        1
  •  0
  •   Ilya Rusin    6 年前

    另一个实现可能是 Difference Lists (也可提供基于序言的解释- Understanding Difference Lists ).

    DList 在Scala中:

    abstract class DiffList[A](calculate: List[A] => List[A]) {
      def prepend(s: List[A]): DiffList[A]
    
      def append(s: List[A]): DiffList[A]
    
      def result: List[A]
    }
    
    final class DiffListImpl[A](listFunc: List[A] => List[A])
        extends DiffList[A](listFunc) {
      def prepend(s: List[A]): DiffListImpl[A] =
        new DiffListImpl[A](listFunc andThen (s ++ _))
    
    
      def append(s: List[A]): DiffListImpl[A] =
        new DiffListImpl[A](listFunc andThen (_ ++ s))
    
      def result: List[A] = listFunc(Nil)
    }
    

    使用它:

    val l1 = List(1, 2)
    val l2 = List(6, 7)
    val l3 = List(3, 4, 5)
    val dl = new DiffListImpl[Int](Nil)
    
    val result = dl.prepend(l1).prepend(l2).append(l3).result
    
    Result: List(6, 7, 1, 2, 3, 4, 5)
    
    推荐文章