![]() It simply applies the procedure to each List element. Here's a quote about the foreach method from the book Programming in Scala:įoreach takes a procedure (a function with a result type Unit) as the right operand. You can also merge two Scala lists using the List's concat method:Ī very common way to iterate over Scala lists is with the foreach method. This operation is said to have O(n) speed, where n is the number of elements in the first List. First, you can merge two Scala lists using the ::: method of the List class: There are at least two ways to merge Scala Lists. (Again, I recall this approach and syntax from using Lisp many years ago.) Appending and merging Lists You can prepend items to a Scala List using the :: method:Īccording to the Beginning Scala book (and several other sources), prepending items to a list is a "very fast, constant-time, O(1) operation." In summary, you can create a new Scala List with these approaches: Scala> val x = List.tabulate(5)(n => n * n)Īs you can see, that example creates a List of five elements, where the element values are the square of the index of each element (0 becomes 0, 1 becomes 1, 2 becomes 4, 3 becomes 9, and 4 becomes 16). The book Programming in Scala shows how to create a List using a simple "squares" function: The tabulate method creates a new List whose elements are created according to the function you supply. X: List = List(foo, foo, foo)įinally, you can create a new List with the tabulate method of the List class. You can also create a new List with its fill method: The range function can also take a third argument which serves as a "step" value when creating the List: You can also create a List with its range method: In this example, I'm explicitly saying that I want the values in the List to be saved as the Number type. ![]() If you're mixing types in a List constructor, you may need to manually specify the List type.
0 Comments
Leave a Reply. |