Saturday 30 August 2014

Scala Note 25: Lists

  1. Lists are immutable.
  2. Elements of a list cannot be changed by assignment.
  3. Lists have a recursive structure, whereas arrays are flat.
  4. Lists support more operations than arrays
All lists are built from two more fundamental constructors, Nil and :: (pronounced “cons”). Nil represents an empty list. The infix operator ::expresses list extension.The ‘::’ operation associates to the right: A :: B :: C is interpreted as A :: (B :: C).

List is an abstract class and is co-variant in this parameter, which means that List[S] <: List[T] for all types S and T such that S <: T.


Higher-Order Methods
xs is a List

xs map (x => x * factor)
xs foreach (x => println(x))
xs filter (x => x > 0)

def isPrime(n: Int) = List.range(2, n) forall (x => n % x != 0)

reduceLeft expand to left-leaning trees. This method inserts a given binary operator between
adjacent elements of a given list.

def sum(xs: List[Int]) = (0 :: xs) reduceLeft {(x, y) => x + y}
def product(xs: List[Int]) = (1 :: xs) reduceLeft {(x, y) => x * y}

No comments:

Post a Comment