Preferred way to create a Scala list

后端 未结 10 2558
走了就别回头了
走了就别回头了 2020-12-02 04:31

There are several ways to construct an immutable list in Scala (see contrived example code below). You can use a mutable ListBuffer, create a var list and modif

相关标签:
10条回答
  • 2020-12-02 05:29

    You want to focus on immutability in Scala generally by eliminating any vars. Readability is still important for your fellow man so:

    Try:

    scala> val list = for(i <- 1 to 10) yield i
    list: scala.collection.immutable.IndexedSeq[Int] = Vector(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
    

    You probably don't even need to convert to a list in most cases :)

    The indexed seq will have everything you need:

    That is, you can now work on that IndexedSeq:

    scala> list.foldLeft(0)(_+_)
    res0: Int = 55
    
    0 讨论(0)
  • 2020-12-02 05:30

    Note: This answer is written for an old version of Scala.

    The Scala collection classes are going to be redesigned as of Scala 2.8, so be prepared to change the way you create lists very soon.

    What is the forward compatible way of creating a List? I have no idea since I haven't read the 2.8 docs yet.

    A PDF document describing the proposed changes of the collection classes

    0 讨论(0)
  • 2020-12-02 05:30

    To create a list of string, use the following:

    val l = List("is", "am", "are", "if")
    
    0 讨论(0)
  • As a new scala developer i wrote small test to check list creation time with suggested methods above. It looks like (for ( p <- ( 0 to x ) ) yield p) toList the fastest approach.

    import java.util.Date
    object Listbm {
    
      final val listSize = 1048576
      final val iterationCounts = 5
      def getCurrentTime: BigInt = (new Date) getTime
    
      def createList[T] ( f : Int => T )( size : Int ): T = f ( size )
    
      // returns function time execution
      def experiment[T] ( f : Int => T ) ( iterations: Int ) ( size :Int ) : Int  = {
    
        val start_time = getCurrentTime
        for ( p <- 0 to iterations )  createList ( f ) ( size )
        return (getCurrentTime - start_time) toInt
    
      }
    
      def printResult ( f:  => Int ) : Unit = println ( "execution time " + f  )
    
      def main( args : Array[String] ) {
    
    
        args(0) match {
    
          case "for" =>  printResult ( experiment ( x => (for ( p <- ( 0 to x ) ) yield p) toList  ) ( iterationCounts ) ( listSize ) )
          case "range"  =>  printResult ( experiment ( x => ( 0 to x ) toList ) ( iterationCounts ) ( listSize ) )
          case "::" => printResult ( experiment ( x => ((0 to x) :\ List[Int]())(_ :: _) ) ( iterationCounts ) ( listSize ) )
          case _ => println ( "please use: for, range or ::\n")
        }
      }
    }
    
    0 讨论(0)
提交回复
热议问题