map- xs.map (x => "0x%02x".format(x))
foreach- xs.foreach (x => println ("0x%02x".format(x)))
yield- for x <- xs yield "0x%02x".format(x)
do- for x <- xs do println ("0x%02x".format(x))
Copy only elements that satisfy a predicate f
- def filter [X] (xs:List[X], f:X=>Boolean) : List[X] = xs match
- case Nil => Nil
- case y::ys if f (y) => y :: filter (ys, f)
- case _::ys => filter (ys, f)
- val zs = (0 to 7).toList
- filter(zs, ((_:Int) % 3 != 0))
filter- zs.filter (z => z % 3 != 0) // shorter: zs.filter(_ % 3 != 0)
- zs.filter (z => z % 3 != 0).map (z => "0x%02x".format(z))
- for z <- zs; if z % 3 != 0 yield z
- for z <- zs; if z % 3 != 0 yield "0x%02x".format(z)
Multiple iterators
- val xss = List(List(11,21,31),List(),List(41,51))
- for xs <- xss; x <- xs yield (x, xs.length)
- res1: List[(Int, Int)] = List((11,3), (21,3), (31,3), (41,2), (51,2))
Cross product of independent iterators
- val xs = List(11,21,31)
- val ys = List("a","b")
- for x <- xs; y <- ys yield (x, y)
- res1: List[(Int, String)] = List((11,a), (11,b), (21,a), (21,b), (31,a), (31,b))
- (for x <- (1 to 7);
- y <- (1 to 9) yield (x, y)).length
- res1: Int = 63
- val xs = List(11,21,31)
- val ys = List("a","b")
- for x <- xs;
- y <- ys yield (x, y)
xs : List[Int]ys : List[String]- x : Int
- y : String
yield provides the type for the result- (x, y) : (Int, String)
- for ... yield (x, y) : List[(Int, String)]
foreach, map, etc. as argumentRevisit the copy operation
- def copy [X] (xs:List[List[X]]) : List[List[X]] = xs match
- case Nil => Nil
- case y::ys => y :: copy (ys)
- val xss = List(List(11,21,31),List(),List(41,51))
- copy(xss)
- res1: List(List(11,21,31),List(),List(41,51))
Create a copy with a flat structure: replace :: with :::
- def flatten [X] (xs:List[List[X]]) : List[X] = xs match
- case Nil => Nil
- case y::ys => y ::: flatten (ys)
- val xss = List(List(11,21,31),List(),List(41,51))
- flatten(xss)
- res1: List(11,21,31,41,51)
Revisit method map
- def map [X,Y] (xs:List[X], f:X=>List[Y]) : List[List[Y]] = xs match
- case Nil => Nil
- case y::ys => f(y) :: map (ys, f)
- val as = List(3,0,2)
- map (as, (x:Int) => (1 to x).toList)
- res1: List(List(1,2,3), List(), List(1,2))
Create a transformed list with a flat structure: replace :: with :::
- def flatMap [X,Y] (xs:List[X], f:X=>List[Y]) : List[Y] = xs match
- case Nil => Nil
- case y::ys => f(y) ::: flatMap (ys, f)
- val as = List(3,0,2)
- flatMap(as, (x:Int) => (1 to x).toList)
- res1: List(1,2,3,1,2):::Nil
Argument and return types of map and flatMap
map: (List[X],X=>List[Y]) => List[List[Y]]
List[Y]xsflatMap: (List[X],X=>List[Y]) => List[Y]
YList[Y]flatMap- xss.flatMap (x=>x) // same as xss.flatten
- for xs <- xss; x <- xs yield x