Friday, January 6, 2012

Learning Scala : It's easy!

Authored by Win Myo Htet



I have read some comment on SO about how they have learned a new language. One commenter said that a week is too short, yet, somehow the management expect that people learn a new language in a week. Some smart people chime in and said that how they have acquired a new language: "Java in 3 days", "C++ in one week" or "given a C++ book after the successful interview to start coding in it when the individual begins the work (the time difference between the interview date and starting date not given)", "(relevant or not about acquiring a new language) one was given some circuit board on interview". There even is a book "Seven Languages in Seven Weeks". I cannot learn seven language in seven weeks . Well, definitely I am not in a smart camp. I am an average one. There is a well developed theory and term for programmer like me, I think. Something like COTM or something.

It takes me over a month to learn Scala. I don't claim to know all now. I don't know if my lack of academic background in CS or my lack of exposure to functional programming has lengthen the time to learn Scala. Definitely, I can say that Scala is not hard. Then, it must be easy! Learning on my own (as norm in this industry), I stumbles here and there. For example, I should have at least browsed the Scala List API for available functions. There also is a balancing act between functional programming and OO paradigm. I think, that's where a lot of people stumble too. After all, the functional programming paradigm with its immutability make the imperative programmer felt being hand cuffed and they get obsessed with the restraint such that they fail to see how it is liberating them from corruption of data. Twitter has done a good job of balancing between the two. I have gone through some of their open source projects on github and analyze their usage.

Twitter usage is not very far off from imperative domain. They make use of Scala pattern matching a lot to its effect and not afraid to use mutability when it is needed. After all, Scala has given such elasticity. Talking about Scala elasticity, Lift framework, a popular Scala open source web framework, tips toward functional programming side. There is nothing wrong with both approaches. It depends upon how much one is familiar with the functional programming and how much one want to leverage the edge that functional programming give. I have also seen people writing imperative code in Scala and said "Why bother?". "Yeah, why bother?" Though I am looking toward for the day when I can use more functional programming stuff, my pragmatic side make me settled on the Twitter's approach of the mix paradigm. After all, the poor pure functional programming language has to be quite inventive to address some of the taken-for-granted-feature from imperative world. Trust me I want to learn that language too, just to be in cloud nine.

If I can travel back over a month time  to guide me, there won't be much to tell my old self except to skim through the Scala List API at least once and to have a balanced approached to functional programming and OO paradigm. Everything else I have been doing have been on a right track, like not using any IDE and taking advantage of Scala REPL, getting my hand dirty writing code with Scala,  read some blog (definitely avoid the political ones!), write some blog (it forces you to have clarity of understanding on the thing you write.) and read some codes too.

Learning Scala makes me a better programmer by being exposed to a different  paradigm and knowledge.  There is nothing much else to say. I have to admit that I have to make some conscious effort to learn Scala since I am not omniscience.




Authored by Win Myo Htet

Learning Scala : Scala List API with sample code snippet

Authored by Win Myo Htet


We have gone through all the functions of List API and along the way we have skipped around to organize functions in a logical way, thus making it hard to remember which blog covers which function. To alleviate such navigation pain, here is the List API functions list with hyper link to the blog covering the function. If you have not known how to read the scaladoc, it is recommended that you go through the first few blogs where some of the stuff like implicit and lower bound are covered. The later blogs assumed that these information does not need to be repeated.


Type Members
class WithFilter extends FilterMonadic[A, Repr]
A class supporting filtered operations.

Abstract Value Members
def productArity : Int
The size of this product.
def productElement (n: Int): Any
The nth element of this product, 0-based.

Concrete Value Members
def ++ [B] (that: GenTraversableOnce[B]): List[B]
[use case] Concatenates this list with the elements of a traversable collection.
def ++ [B >: A, That] (that: GenTraversableOnce[B])(implicit bf: CanBuildFrom[List[A], B, That]): That
Concatenates this list with the elements of a traversable collection.
def ++ [B >: A, That] (that: TraversableOnce[B])(implicit bf: CanBuildFrom[List[A], B, That]): That
def ++: [B >: A, That] (that: Traversable[B])(implicit bf: CanBuildFrom[List[A], B, That]): That
This overload exists because: for the implementation of ++: we should reuse that of ++ because many collections override it with more efficient versions.
def ++: [B] (that: TraversableOnce[B]): List[B]
[use case] Concatenates this list with the elements of a traversable collection.
def ++: [B >: A, That] (that: TraversableOnce[B])(implicit bf: CanBuildFrom[List[A], B, That]): That
Concatenates this list with the elements of a traversable collection.
def +: (elem: A): List[A]
[use case] Prepends an element to this list
def +: [B >: A, That] (elem: B)(implicit bf: CanBuildFrom[List[A], B, That]): That
Prepends an element to this list
def /: [B] (z: B)(op: (B, A) ⇒ B): B
Applies a binary operator to a start value and all elements of this list, going left to right.
def /:\ [A1 >: A] (z: A1)(op: (A1, A1) ⇒ A1): A1
A syntactic sugar for out of order folding.
def :+ (elem: A): List[A]
[use case] Appends an element to this list
def :+ [B >: A, That] (elem: B)(implicit bf: CanBuildFrom[List[A], B, That]): That
Appends an element to this list
def :: (x: A): List[A]
[use case] Adds an element at the beginning of this list.
def :: [B >: A] (x: B): List[B]
Adds an element at the beginning of this list.
def ::: (prefix: List[A]): List[A]
[use case] Adds the elements of a given list in front of this list.
def ::: [B >: A] (prefix: List[B]): List[B]
Adds the elements of a given list in front of this list.
def :\ [B] (z: B)(op: (A, B) ⇒ B): B
Applies a binary operator to all elements of this list and a start value, going right to left.

A
def addString (b: StringBuilder): StringBuilder
Appends all elements of this list to a string builder.
def addString (b: StringBuilder, sep: String): StringBuilder
Appends all elements of this list to a string builder using a separator string.
def addString (b: StringBuilder, start: String, sep: String, end: String): StringBuilder
Appends all elements of this list to a string builder using start, end, and separator strings.
def aggregate [B] (z: B)(seqop: (B, A) ⇒ B, combop: (B, B) ⇒ B): B
Aggregates the results of applying an operator to subsequent elements.
def andThen [C] (k: (A) ⇒ C): PartialFunction[Int, C]
Composes this partial function with a transformation function that gets applied to results of this partial function.
def apply (n: Int): A
Selects an element by its index in the list.

B

C
def canEqual (that: Any): Boolean
Method called from equality methods, so that user-defined subclasses can refuse to be equal to other collections of the same kind.
def collect [B] (pf: PartialFunction[A, B]): List[B]
[use case] Builds a new collection by applying a partial function to all elements of this list on which the function is defined.
def collect [B, That] (pf: PartialFunction[A, B])(implicit bf: CanBuildFrom[List[A], B, That]): That
Builds a new collection by applying a partial function to all elements of this list on which the function is defined.
def collectFirst [B] (pf: PartialFunction[A, B]): Option[B]
Finds the first element of the list for which the given partial function is defined, and applies the partial function to it.
def combinations (n: Int): Iterator[List[A]]
Iterates over combinations.
def companion : GenericCompanion[List]
The factory companion object that builds instances of class List.
def compose [A] (g: (A) ⇒ Int): (A) ⇒ A
Composes two instances of Function1 in a new Function1, with this function applied last.
def contains (elem: Any): Boolean
Tests whether this list contains a given value as an element.
def containsSlice [B] (that: Seq[B]): Boolean
def containsSlice [B] (that: GenSeq[B]): Boolean
Tests whether this list contains a given sequence as a slice.
def copyToArray (xs: Array[A], start: Int, len: Int): Unit
[use case] Copies elements of this list to an array.
def copyToArray [B >: A] (xs: Array[B], start: Int, len: Int): Unit
Copies elements of this list to an array.
def copyToArray (xs: Array[A]): Unit
[use case] Copies values of this list to an array.
def copyToArray [B >: A] (xs: Array[B]): Unit
Copies values of this list to an array.
def copyToArray (xs: Array[A], start: Int): Unit
[use case] Copies values of this list to an array.
def copyToArray [B >: A] (xs: Array[B], start: Int): Unit
Copies values of this list to an array.
def copyToBuffer [B >: A] (dest: Buffer[B]): Unit
Copies all elements of this list to a buffer.
def corresponds [B] (that: Seq[B])(p: (A, B) ⇒ Boolean): Boolean
def corresponds [B] (that: GenSeq[B])(p: (A, B) ⇒ Boolean): Boolean
Tests whether every element of this list relates to the corresponding element of another sequence by satisfying a test predicate.
def count (p: (A) ⇒ Boolean): Int
Counts the number of elements in the list which satisfy a predicate.

D
def diff [B >: A] (that: Seq[B]): List[A]
def diff (that: Seq[A]): List[A]
[use case] Computes the multiset difference between this list and another sequence.
def diff [B >: A] (that: GenSeq[B]): List[A]
Computes the multiset difference between this list and another sequence.
def distinct : List[A]
Builds a new list from this list without any duplicate elements.
def drop (n: Int): List[A]
Selects all elements except first n ones.
def dropRight (n: Int): List[A]
Selects all elements except last n ones.
def dropWhile (p: (A) ⇒ Boolean): List[A]
Drops longest prefix of elements that satisfy a predicate.

E
def endsWith [B] (that: Seq[B]): Boolean
def endsWith [B] (that: GenSeq[B]): Boolean
Tests whether this list ends with the given sequence.
def equals (that: Any): Boolean
The equals method for arbitrary sequences.
def exists (p: (A) ⇒ Boolean): Boolean
Tests whether a predicate holds for some of the elements of this list.

F
def filter (p: (A) ⇒ Boolean): List[A]
Selects all elements of this list which satisfy a predicate.
def filterNot (p: (A) ⇒ Boolean): List[A]
Selects all elements of this list which do not satisfy a predicate.
def find (p: (A) ⇒ Boolean): Option[A]
Finds the first element of the list satisfying a predicate, if any.
def flatMap [B] (f: (A) ⇒ GenTraversableOnce[B]): List[B]
[use case] Builds a new collection by applying a function to all elements of this list and concatenating the results.
def flatMap [B, That] (f: (A) ⇒ GenTraversableOnce[B])(implicit bf: CanBuildFrom[List[A], B, That]): That
Builds a new collection by applying a function to all elements of this list and concatenating the results.
def flatten [B] : List[B]
[use case] Converts this list of traversable collections into a list in which all element collections are concatenated.
def flatten [B] (implicit asTraversable: (A) ⇒ TraversableOnce[B]): Traversable[B]
Converts this list of traversable collections into a list in which all element collections are concatenated.
def fold [A1 >: A] (z: A1)(op: (A1, A1) ⇒ A1): A1
Folds the elements of this sequence using the specified associative binary operator.
def foldLeft [B] (z: B)(f: (B, A) ⇒ B): B
Applies a binary operator to a start value and all elements of this list, going left to right.
def foldRight [B] (z: B)(f: (A, B) ⇒ B): B
Applies a binary operator to all elements of this list and a start value, going right to left.
def forall (p: (A) ⇒ Boolean): Boolean
Tests whether a predicate holds for all elements of this list.
def foreach (f: (A) ⇒ Unit): Unit
[use case] Applies a function f to all elements of this list.
def foreach [B] (f: (A) ⇒ B): Unit
Applies a function f to all elements of this list.

G
def genericBuilder [B] : Builder[B, List[B]]
The generic builder that builds instances of List at arbitrary element types.
def groupBy [K] (f: (A) ⇒ K): Map[K, List[A]]
Partitions this list into a map of lists according to some discriminator function.
def grouped (size: Int): Iterator[List[A]]
Partitions elements in fixed size lists.

H
def hasDefiniteSize : Boolean
Tests whether this list is known to have a finite size.
def hashCode (): Int
Hashcodes for List produce a value from the hashcodes of all the elements of the list.
def head : A
Selects the first element of this list.
def headOption : Option[A]
Optionally selects the first element.

I
def indexOf (elem: A, from: Int): Int
[use case] Finds index of first occurrence of some value in this list after or at some start index.
def indexOf [B >: A] (elem: B, from: Int): Int
Finds index of first occurrence of some value in this list after or at some start index.
def indexOf (elem: A): Int
[use case] Finds index of first occurrence of some value in this list.
def indexOf [B >: A] (elem: B): Int
Finds index of first occurrence of some value in this list.
def indexOfSlice [B >: A] (that: Seq[B], from: Int): Int
def indexOfSlice [B >: A] (that: GenSeq[B], from: Int): Int
Finds first index after or at a start index where this list contains a given sequence as a slice.
def indexOfSlice [B >: A] (that: Seq[B]): Int
def indexOfSlice [B >: A] (that: GenSeq[B]): Int
Finds first index where this list contains a given sequence as a slice.
def indexWhere (p: (A) ⇒ Boolean, from: Int): Int
Finds index of the first element satisfying some predicate after or at some start index.
def indexWhere (p: (A) ⇒ Boolean): Int
Finds index of first element satisfying some predicate.
def indices : Range
Produces the range of all indices of this sequence.
def init : List[A]
Selects all elements except the last.
def inits : Iterator[List[A]]
Iterates over the inits of this list.
def intersect [B >: A] (that: Seq[B]): List[A]
def intersect (that: Seq[A]): List[A]
[use case] Computes the multiset intersection between this list and another sequence.
def intersect [B >: A] (that: GenSeq[B]): List[A]
Computes the multiset intersection between this list and another sequence.
def isDefinedAt (x: Int): Boolean
Tests whether this list contains given index.
def isEmpty : Boolean
Tests whether the list is empty.
def isTraversableAgain : Boolean
Tests whether this list can be repeatedly traversed.
def iterator : Iterator[A]
Creates a new iterator over all elements contained in this iterable object.

J

K

L
def last : A
Selects the last element.
def lastIndexOf (elem: A, end: Int): Int
[use case] Finds index of last occurrence of some value in this list before or at a given end index.
def lastIndexOf [B >: A] (elem: B, end: Int): Int
Finds index of last occurrence of some value in this list before or at a given end index.
def lastIndexOf (elem: A): Int
[use case] Finds index of last occurrence of some value in this list.
def lastIndexOf [B >: A] (elem: B): Int
Finds index of last occurrence of some value in this list.
def lastIndexOfSlice [B >: A] (that: Seq[B], end: Int): Int
def lastIndexOfSlice [B >: A] (that: GenSeq[B], end: Int): Int
Finds last index before or at a given end index where this list contains a given sequence as a slice.
def lastIndexOfSlice [B >: A] (that: Seq[B]): Int
def lastIndexOfSlice [B >: A] (that: GenSeq[B]): Int
Finds last index where this list contains a given sequence as a slice.
def lastIndexWhere (p: (A) ⇒ Boolean, end: Int): Int
Finds index of last element satisfying some predicate before or at given end index.
def lastIndexWhere (p: (A) ⇒ Boolean): Int
Finds index of last element satisfying some predicate.
def lastOption : Option[A]
Optionally selects the last element.
def length : Int
The length of the list.
def lengthCompare (len: Int): Int
Compares the length of this list to a test value.
def lift : (Int) ⇒ Option[A]
Turns this partial function into an plain function returning an Option result.

M
def map [B] (f: (A) ⇒ B): List[B]
[use case] Builds a new collection by applying a function to all elements of this list.
def map [B, That] (f: (A) ⇒ B)(implicit bf: CanBuildFrom[List[A], B, That]): That
Builds a new collection by applying a function to all elements of this list.
def mapConserve (f: (A) ⇒ A): List[A]
[use case] Builds a new list by applying a function to all elements of this list.
def mapConserve [B >: A <: AnyRef] (f: (A) ⇒ B): List[B]
Builds a new list by applying a function to all elements of this list.
def max : A
[use case] Finds the largest element.
def max [B >: A] (implicit cmp: Ordering[B]): A
Finds the largest element.
def maxBy [B] (f: (A) ⇒ B)(implicit cmp: Ordering[B]): A
def min : A
[use case] Finds the smallest element.
def min [B >: A] (implicit cmp: Ordering[B]): A
Finds the smallest element.
def minBy [B] (f: (A) ⇒ B)(implicit cmp: Ordering[B]): A
def mkString : String
Displays all elements of this list in a string.
def mkString (sep: String): String
Displays all elements of this list in a string using a separator string.
def mkString (start: String, sep: String, end: String): String
Displays all elements of this list in a string using start, end, and separator strings.

N
def nonEmpty : Boolean
Tests whether the list is not empty.

O
def orElse [A1 <: Int, B1 >: A] (that: PartialFunction[A1, B1]): PartialFunction[A1, B1]
Composes this partial function with a fallback partial function which gets applied where this partial function is not defined.

P
def padTo (len: Int, elem: A): List[A]
[use case] Appends an element value to this list until a given target length is reached.
def padTo [B >: A, That] (len: Int, elem: B)(implicit bf: CanBuildFrom[List[A], B, That]): That
Appends an element value to this list until a given target length is reached.
def par : ParSeq[A]
Returns a parallel implementation of this collection.
def partition (p: (A) ⇒ Boolean): (List[A], List[A])
Partitions this list in two lists according to a predicate.
def patch [B >: A, That] (from: Int, patch: Seq[B], replaced: Int)(implicit bf: CanBuildFrom[List[A], B, That]): That
def patch (from: Int, that: GenSeq[A], replaced: Int): List[A]
[use case] Produces a new list where a slice of elements in this list is replaced by another sequence.
def patch [B >: A, That] (from: Int, patch: GenSeq[B], replaced: Int)(implicit bf: CanBuildFrom[List[A], B, That]): That
Produces a new list where a slice of elements in this list is replaced by another sequence.
def permutations : Iterator[List[A]]
Iterates over distinct permutations.
def prefixLength (p: (A) ⇒ Boolean): Int
Returns the length of the longest prefix whose elements all satisfy some predicate.
def product : A
[use case] Multiplies up the elements of this collection.
def product [B >: A] (implicit num: Numeric[B]): B
Multiplies up the elements of this collection.
def productIterator : Iterator[Any]
An iterator over all the elements of this product.
def productPrefix : String
A string used in the toString methods of derived classes.

Q

R
def reduce [A1 >: A] (op: (A1, A1) ⇒ A1): A1
Reduces the elements of this sequence using the specified associative binary operator.
def reduceLeft [B >: A] (f: (B, A) ⇒ B): B
def reduceLeftOption [B >: A] (op: (B, A) ⇒ B): Option[B]
Optionally applies a binary operator to all elements of this list, going left to right.
def reduceOption [A1 >: A] (op: (A1, A1) ⇒ A1): Option[A1]
Optionally reduces the elements of this sequence using the specified associative binary operator.
def reduceRight [B >: A] (op: (A, B) ⇒ B): B
Applies a binary operator to all elements of this list, going right to left.
def reduceRightOption [B >: A] (op: (A, B) ⇒ B): Option[B]
Optionally applies a binary operator to all elements of this list, going right to left.
def repr : List[A]
The collection of type list underlying this TraversableLike object.
def reverse : List[A]
Returns new list wih elements in reversed order.
def reverseIterator : Iterator[A]
An iterator yielding elements in reversed order.
def reverseMap [B] (f: (A) ⇒ B): List[B]
[use case] Builds a new collection by applying a function to all elements of this list and collecting the results in reversed order.
def reverseMap [B, That] (f: (A) ⇒ B)(implicit bf: CanBuildFrom[List[A], B, That]): That
Builds a new collection by applying a function to all elements of this list and collecting the results in reversed order.
def reverse_::: (prefix: List[A]): List[A]
[use case] Adds the elements of a given list in reverse order in front of this list.
def reverse_::: [B >: A] (prefix: List[B]): List[B]
Adds the elements of a given list in reverse order in front of this list.

S
def sameElements (that: GenIterable[A]): Boolean
[use case] Checks if the other iterable collection contains the same elements in the same order as this list.
def sameElements [B >: A] (that: GenIterable[B]): Boolean
Checks if the other iterable collection contains the same elements in the same order as this list.
def sameElements [B >: A] (that: Iterable[B]): Boolean
def scan [B >: A, That] (z: B)(op: (B, B) ⇒ B)(implicit cbf: CanBuildFrom[List[A], B, That]): That
Computes a prefix scan of the elements of the collection.
def scanLeft [B, That] (z: B)(op: (B, A) ⇒ B)(implicit bf: CanBuildFrom[List[A], B, That]): That
Produces a collection containing cummulative results of applying the operator going left to right.
def scanRight [B, That] (z: B)(op: (A, B) ⇒ B)(implicit bf: CanBuildFrom[List[A], B, That]): That
Produces a collection containing cummulative results of applying the operator going right to left.
def segmentLength (p: (A) ⇒ Boolean, from: Int): Int
Computes length of longest segment whose elements all satisfy some predicate.
def seq : Seq[A]
A version of this collection with all of the operations implemented sequentially (i.
def size : Int
The size of this list, equivalent to length.
def slice (from: Int, until: Int): List[A]
Selects an interval of elements.
def sliding [B >: A] (size: Int, step: Int): Iterator[List[A]]
def sliding [B >: A] (size: Int): Iterator[List[A]]
Groups elements in fixed size blocks by passing a "sliding window" over them (as opposed to partitioning them, as is done in grouped.
def sortBy [B] (f: (A) ⇒ B)(implicit ord: Ordering[B]): List[A]
Sorts this List according to the Ordering which results from transforming an implicitly given Ordering with a transformation function.
def sortWith (lt: (A, A) ⇒ Boolean): List[A]
Sorts this list according to a comparison function.
def sorted [B >: A] (implicit ord: Ordering[B]): List[A]
Sorts this list according to an Ordering.
def span (p: (A) ⇒ Boolean): (List[A], List[A])
Splits this list into a prefix/suffix pair according to a predicate.
def splitAt (n: Int): (List[A], List[A])
Splits this list into two at a given position.
def startsWith [B] (that: Seq[B], offset: Int): Boolean
def startsWith [B] (that: GenSeq[B], offset: Int): Boolean
Tests whether this list contains the given sequence at a given index.
def startsWith [B] (that: Seq[B]): Boolean
def startsWith [B] (that: GenSeq[B]): Boolean
Tests whether this list starts with the given sequence.
def stringPrefix : String
Defines the prefix of this object's toString representation.
def sum : A
[use case] Sums up the elements of this collection.
def sum [B >: A] (implicit num: Numeric[B]): B
Sums up the elements of this collection.

T
def tail : List[A]
Selects all elements except the first.
def tails : Iterator[List[A]]
Iterates over the tails of this list.
def take (n: Int): List[A]
Selects first n elements.
def takeRight (n: Int): List[A]
Selects last n elements.
def takeWhile (p: (A) ⇒ Boolean): List[A]
Takes longest prefix of elements that satisfy a predicate.
def toArray : Array[A]
[use case] Converts this list to an array.
def toArray [B >: A] (implicit arg0: ClassManifest[B]): Array[B]
Converts this list to an array.
def toBuffer [B >: A] : Buffer[B]
Converts this list to a mutable buffer.
def toIndexedSeq [B >: A] : IndexedSeq[B]
Converts this list to an indexed sequence.
def toIterable : Iterable[A]
Converts this list to an iterable collection.
def toIterator : Iterator[A]
Returns an Iterator over the elements in this list.
def toList : List[A]
Converts this list to a list.
def toMap [T, U] : Map[T, U]
[use case] Converts this list to a map.
def toMap [T, U] (implicit ev: <:<[A, (T, U)]): Map[T, U]
Converts this list to a map.
def toSeq : Seq[A]
Converts this list to a sequence.
def toSet [B >: A] : Set[B]
Converts this list to a set.
def toStream : Stream[A]
Converts this list to a stream.
def toString (): String
Converts this list to a string.
def toTraversable : Traversable[A]
Converts this list to an unspecified Traversable.
def transpose [B] (implicit asTraversable: (A) ⇒ TraversableOnce[B]): Traversable[Traversable[B]]
Transposes this list of traversable collections into a list of lists.

U
def union (that: Seq[A]): List[A]
[use case] Produces a new sequence which contains all elements of this list and also all elements of a given sequence.
def union [B >: A, That] (that: GenSeq[B])(implicit bf: CanBuildFrom[List[A], B, That]): That
Produces a new sequence which contains all elements of this list and also all elements of a given sequence.
def union [B >: A, That] (that: Seq[B])(implicit bf: CanBuildFrom[List[A], B, That]): That
def unzip [A1, A2] (implicit asPair: (A) ⇒ (A1, A2)): (List[A1], List[A2])
Converts this list of pairs into two collections of the first and second half of each pair.
def unzip3 [A1, A2, A3] (implicit asTriple: (A) ⇒ (A1, A2, A3)): (List[A1], List[A2], List[A3])
Converts this list of triples into three collections of the first, second, and third element of each triple.
def updated (index: Int, elem: A): List[A]
[use case] A copy of this list with one single replaced element.
def updated [B >: A, That] (index: Int, elem: B)(implicit bf: CanBuildFrom[List[A], B, That]): That
A copy of this list with one single replaced element.

V
def view (from: Int, until: Int): SeqView[A, List[A]]
Creates a non-strict view of a slice of this list.
def view : SeqView[A, List[A]]
Creates a non-strict view of this list.

W
def withFilter (p: (A) ⇒ Boolean): FilterMonadic[A, List[A]]
Creates a non-strict filter of this list.

X

Y

Z
def zip [A1 >: A, B, That] (that: Iterable[B])(implicit bf: CanBuildFrom[List[A], (A1, B), That]): That
def zip [B] (that: GenIterable[B]): List[(A, B)]
[use case] Returns a list formed from this list and another iterable collection by combining corresponding elements in pairs.
def zip [A1 >: A, B, That] (that: GenIterable[B])(implicit bf: CanBuildFrom[List[A], (A1, B), That]): That
Returns a list formed from this list and another iterable collection by combining corresponding elements in pairs.
def zipAll [B, A1 >: A, That] (that: Iterable[B], thisElem: A1, thatElem: B)(implicit bf: CanBuildFrom[List[A], (A1, B), That]): That
def zipAll [B] (that: Iterable[B], thisElem: A, thatElem: B): List[(A, B)]
[use case] Returns a list formed from this list and another iterable collection by combining corresponding elements in pairs.
def zipAll [B, A1 >: A, That] (that: GenIterable[B], thisElem: A1, thatElem: B)(implicit bf: CanBuildFrom[List[A], (A1, B), That]): That
Returns a list formed from this list and another iterable collection by combining corresponding elements in pairs.
def zipWithIndex : List[(A, Int)]
[use case] Zips this list with its indices.
def zipWithIndex [A1 >: A, That] (implicit bf: CanBuildFrom[List[A], (A1, Int), That]): That
Zips this list with its indices.



Authored by Win Myo Htet

Thursday, January 5, 2012

Learning Scala : Reading the exotic and essential List API scaladoc 14

Authored by Win Myo Htet



Having gone through the needed explanation in the beginning of the series, there is little need to elaborate for most of the stuff except to show the code snippet. Let's just try to cover all the remaining functions in this blog since it has been a long series!

def max : A
[use case] Finds the largest element.
def max [B >: A] (implicit cmp: Ordering[B]): A
Finds the largest element.
def maxBy [B] (f: (A) ⇒ B)(implicit cmp: Ordering[B]): A
def min : A
[use case] Finds the smallest element.
def min [B >: A] (implicit cmp: Ordering[B]): A
Finds the smallest element.
def minBy [B] (f: (A) ⇒ B)(implicit cmp: Ordering[B]): A

We can simply call max or min and let the Scala implicit function take care of the comparing or we can convert the element to our liking for unique comparison by using maxBy/minBy.
def padTo (len: Int, elem: A): List[A]
[use case] Appends an element value to this list until a given target length is reached.
def padTo [B >: A, That] (len: Int, elem: B)(implicit bf: CanBuildFrom[List[A], B, That]): That
Appends an element value to this list until a given target length is reached.
def patch [B >: A, That] (from: Int, patch: Seq[B], replaced: Int)(implicit bf: CanBuildFrom[List[A], B, That]): That
def patch (from: Int, that: GenSeq[A], replaced: Int): List[A]
[use case] Produces a new list where a slice of elements in this list is replaced by another sequence.
def patch [B >: A, That] (from: Int, patch: GenSeq[B], replaced: Int)(implicit bf: CanBuildFrom[List[A], B, That]): That
Produces a new list where a slice of elements in this list is replaced by another sequence.
def permutations : Iterator[List[A]]
Iterates over distinct permutations.

def repr : List[A]
The collection of type list underlying this TraversableLike object.
def reverse : List[A]
Returns new list wih elements in reversed order.
def reverseIterator : Iterator[A]
An iterator yielding elements in reversed order.
def reverseMap [B] (f: (A) ⇒ B): List[B]
[use case] Builds a new collection by applying a function to all elements of this list and collecting the results in reversed order.
def reverseMap [B, That] (f: (A) ⇒ B)(implicit bf: CanBuildFrom[List[A], B, That]): That
Builds a new collection by applying a function to all elements of this list and collecting the results in reversed order.
def reverse_::: (prefix: List[A]): List[A]
[use case] Adds the elements of a given list in reverse order in front of this list.
def reverse_::: [B >: A] (prefix: List[B]): List[B]
Adds the elements of a given list in reverse order in front of this list.

scala> val list = (for (i <- 1 to 11) yield i) toList
list: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11)

scala> list min
res0: Int = 1

scala> list max
res1: Int = 11

scala> list minBy {x => -x}
res2: Int = 11

scala> list padTo (19,11)
res3: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11)

scala> list padTo (19,'a')
res4: List[AnyVal] = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, a, a, a, a, a, a, a, a)

scala> list patch (5,List('a','b','c'),3)
res5: List[AnyVal{def getClass(): java.lang.Class[_ >: Int with Char <: AnyVal]}] = List(1, 2, 3, 4, 5, a, b, c, 9, 10, 11)

scala> list patch (5,List('a','b','c'),1)
res6: List[AnyVal{def getClass(): java.lang.Class[_ >: Int with Char <: AnyVal]}] = List(1, 2, 3, 4, 5, a, b, c, 7, 8, 9, 10, 11)

scala> list repr
res7: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11)

scala>  list reverse
res8: List[Int] = List(11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1)

scala> for (i <- list reverseIterator) println(i)
11
10
9
8
7
6
5
4
3
2
1

scala> list reverseMap { x => "-"+x+"-"}
res10: List[java.lang.String] = List(-11-, -10-, -9-, -8-, -7-, -6-, -5-, -4-, -3-, -2-, -1-)

scala> list.reverse:::(List('a','b','c'))
res11: List[AnyVal{def getClass(): java.lang.Class[_ >: Char with Int <: AnyVal]}] = List(11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, a, b, c)

scala> val pl=List(1,2,3)
pl: List[Int] = List(1, 2, 3)

scala> (pl permutations) toList
res12: List[List[Int]] = List(List(1, 2, 3), List(1, 3, 2), List(2, 1, 3), List(2, 3, 1), List(3, 1, 2), List(3, 2, 1))



We will start a new repl session for the rest of the functions.
def segmentLength (p: (A) ⇒ Boolean, from: Int): Int
Computes length of longest segment whose elements all satisfy some predicate.
def seq : Seq[A]
A version of this collection with all of the operations implemented sequentially (i.
def size : Int
The size of this list, equivalent to length.
def slice (from: Int, until: Int): List[A]
Selects an interval of elements.
def sortBy [B] (f: (A) ⇒ B)(implicit ord: Ordering[B]): List[A]
Sorts this List according to the Ordering which results from transforming an implicitly given Ordering with a transformation function.
def sortWith (lt: (A, A) ⇒ Boolean): List[A]
Sorts this list according to a comparison function.
def sorted [B >: A] (implicit ord: Ordering[B]): List[A]
Sorts this list according to an Ordering.
def span (p: (A) ⇒ Boolean): (List[A], List[A])
Splits this list into a prefix/suffix pair according to a predicate.
def splitAt (n: Int): (List[A], List[A])
Splits this list into two at a given position.

scala>  val list = List('a','b','c','c','c','d','e','f','g','h','c','j','k','c','l','m')
list: List[Char] = List(a, b, c, c, c, d, e, f, g, h, c, j, k, c, l, m)

scala> list segmentLength({x => x == 'c'},0)
res0: Int = 0

scala> list segmentLength({x => x == 'c'},2)
res1: Int = 3

scala> list seq
res2: scala.collection.immutable.Seq[Char] = List(a, b, c, c, c, d, e, f, g, h, c, j, k, c, l, m)

scala> list size
res3: Int = 16

scala> list slice(3,8)
res4: List[Char] = List(c, c, d, e, f)

scala> list sorted
res5: List[Char] = List(a, b, c, c, c, c, c, d, e, f, g, h, j, k, l, m)

scala> val intl= List(3,2,5,4,8,0,4,1,5,76,9,0,4,3,2,24,45,657)
intl: List[Int] = List(3, 2, 5, 4, 8, 0, 4, 1, 5, 76, 9, 0, 4, 3, 2, 24, 45, 657)

scala> intl sorted
res6: List[Int] = List(0, 0, 1, 2, 2, 3, 3, 4, 4, 4, 5, 5, 8, 9, 24, 45, 76, 657)

scala> intl sortBy {x => -x}
res7: List[Int] = List(657, 76, 45, 24, 9, 8, 5, 5, 4, 4, 4, 3, 3, 2, 2, 1, 0, 0)

scala> intl sortWith {(x,y) => x < y}
res8: List[Int] = List(0, 0, 1, 2, 2, 3, 3, 4, 4, 4, 5, 5, 8, 9, 24, 45, 76, 657)

scala> (intl sorted) span {x => x % 2 == 0}
res9: (List[Int], List[Int]) = (List(0, 0),List(1, 2, 2, 3, 3, 4, 4, 4, 5, 5, 8, 9, 24, 45, 76, 657))

scala> (intl sorted) span {x => x < 10}
res10: (List[Int], List[Int]) = (List(0, 0, 1, 2, 2, 3, 3, 4, 4, 4, 5, 5, 8, 9),List(24, 45, 76, 657))

scala> intl splitAt 7
res11: (List[Int], List[Int]) = (List(3, 2, 5, 4, 8, 0, 4),List(1, 5, 76, 9, 0, 4, 3, 2, 24, 45, 657))

scala> val words = "The quick brown fox jumped over the lazy dog".split(' ')
words: Array[String] = Array(The, quick, brown, fox, jumped, over, the, lazy, dog)

scala> words.sortBy(x => (x.length, x.head))
res12: Array[String] = Array(The, dog, fox, the, lazy, over, brown, quick, jumped)

scala> List("Steve", "Tom", "John", "Bob").sortWith(_.compareTo(_) < 0) 
res13: List[java.lang.String] = List(Bob, John, Steve, Tom)


For the function toMap, the elements have to be tuple of 2 but I am lazy to create such List and instead, use the function zip, which we will see next.
def toArray : Array[A]
[use case] Converts this list to an array.
def toArray [B >: A] (implicit arg0: ClassManifest[B]): Array[B]
Converts this list to an array.
def toBuffer [B >: A] : Buffer[B]
Converts this list to a mutable buffer.
def toIndexedSeq [B >: A] : IndexedSeq[B]
Converts this list to an indexed sequence.
def toIterable : Iterable[A]
Converts this list to an iterable collection.
def toIterator : Iterator[A]
Returns an Iterator over the elements in this list.
def toList : List[A]
Converts this list to a list.
def toMap [T, U] : Map[T, U]
[use case] Converts this list to a map.
def toMap [T, U] (implicit ev: <:<[A, (T, U)]): Map[T, U]
Converts this list to a map.
def toSeq : Seq[A]
Converts this list to a sequence.
def toSet [B >: A] : Set[B]
Converts this list to a set.
def toStream : Stream[A]
Converts this list to a stream.
def toString (): String
Converts this list to a string.
def toTraversable : Traversable[A]
Converts this list to an unspecified Traversable.
def transpose [B] (implicit asTraversable: (A) ⇒ TraversableOnce[B]): Traversable[Traversable[B]]
Transposes this list of traversable collections into a list of lists.

scala> val list = List('a','b','c','c','c','d','e','f','g','h','c','j','k','c','l','m')
list: List[Char] = List(a, b, c, c, c, d, e, f, g, h, c, j, k, c, l, m)

scala> val intl= List(3,2,5,4,8,0,4,1,5,76,9,0,4,3,2,24,45,657)
intl: List[Int] = List(3, 2, 5, 4, 8, 0, 4, 1, 5, 76, 9, 0, 4, 3, 2, 24, 45, 657)

scala> list toArray
res0: Array[Char] = Array(a, b, c, c, c, d, e, f, g, h, c, j, k, c, l, m)

scala> list toBuffer
res1: scala.collection.mutable.Buffer[Char] = ArrayBuffer(a, b, c, c, c, d, e, f, g, h, c, j, k, c, l, m)

scala> list toIndexedSeq
res2: scala.collection.immutable.IndexedSeq[Char] = Vector(a, b, c, c, c, d, e, f, g, h, c, j, k, c, l, m)

scala> for ( x <- list toIterable) println(x)
a
b
c
c
c
d
e
f
g
h
c
j
k
c
l
m

scala> for ( x <- list toIterator) println(x)
a
b
c
c
c
d
e
f
g
h
c
j
k
c
l
m

scala>  list toList
res5: List[Char] = List(a, b, c, c, c, d, e, f, g, h, c, j, k, c, l, m)

scala> (list zip intl) toMap
res6: scala.collection.immutable.Map[Char,Int] = Map(e -> 4, j -> 0, f -> 1, a -> 3, m -> 24, b -> 2, g -> 5, l -> 2, c -> 3, h -> 76, k -> 4, d -> 0)

scala> list toSeq
res7: scala.collection.immutable.Seq[Char] = List(a, b, c, c, c, d, e, f, g, h, c, j, k, c, l, m)

scala> list toSet
res8: scala.collection.immutable.Set[Char] = Set(e, j, f, a, m, b, g, l, c, h, k, d)

scala> list toStream
res9: scala.collection.immutable.Stream[Char] = Stream(a, ?)

scala> list toString
res10: String = List(a, b, c, c, c, d, e, f, g, h, c, j, k, c, l, m)

scala> for (x <- list toTraversable) println(x)
a
b
c
c
c
d
e
f
g
h
c
j
k
c
l
m

scala> val l = List(List(1, 2, 3), List(4, 5,6), List(7, 8, 9))
l: List[List[Int]] = List(List(1, 2, 3), List(4, 5, 6), List(7, 8, 9))

scala> l.transpose
res12: List[List[Int]] = List(List(1, 4, 7), List(2, 5, 8), List(3, 6, 9))


I didn't know that Scala have zip and Stream as an infinite List when I am writing "Learning Scala: doing Scala exercise from Haskell's example". Should have gone through List API before!
def unzip [A1, A2] (implicit asPair: (A) ⇒ (A1, A2)): (List[A1], List[A2])
Converts this list of pairs into two collections of the first and second half of each pair.
def unzip3 [A1, A2, A3] (implicit asTriple: (A) ⇒ (A1, A2, A3)): (List[A1], List[A2], List[A3])
Converts this list of triples into three collections of the first, second, and third element of each triple.
def updated (index: Int, elem: A): List[A]
[use case] A copy of this list with one single replaced element.
def updated [B >: A, That] (index: Int, elem: B)(implicit bf: CanBuildFrom[List[A], B, That]): That
A copy of this list with one single replaced element.
def view (from: Int, until: Int): SeqView[A, List[A]]
Creates a non-strict view of a slice of this list.
def view : SeqView[A, List[A]]
Creates a non-strict view of this list.
def zip [A1 >: A, B, That] (that: Iterable[B])(implicit bf: CanBuildFrom[List[A], (A1, B), That]): That
def zip [B] (that: GenIterable[B]): List[(A, B)]
[use case] Returns a list formed from this list and another iterable collection by combining corresponding elements in pairs.
def zip [A1 >: A, B, That] (that: GenIterable[B])(implicit bf: CanBuildFrom[List[A], (A1, B), That]): That
Returns a list formed from this list and another iterable collection by combining corresponding elements in pairs.
def zipAll [B, A1 >: A, That] (that: Iterable[B], thisElem: A1, thatElem: B)(implicit bf: CanBuildFrom[List[A], (A1, B), That]): That
def zipAll [B] (that: Iterable[B], thisElem: A, thatElem: B): List[(A, B)]
[use case] Returns a list formed from this list and another iterable collection by combining corresponding elements in pairs.
def zipAll [B, A1 >: A, That] (that: GenIterable[B], thisElem: A1, thatElem: B)(implicit bf: CanBuildFrom[List[A], (A1, B), That]): That
Returns a list formed from this list and another iterable collection by combining corresponding elements in pairs.
def zipWithIndex : List[(A, Int)]
[use case] Zips this list with its indices.
def zipWithIndex [A1 >: A, That] (implicit bf: CanBuildFrom[List[A], (A1, Int), That]): That
Zips this list with its indices.

scala> val list = List('a','b','c','c','c','d','e','f','g','h','c','j','k','c','l','m')
list: List[Char] = List(a, b, c, c, c, d, e, f, g, h, c, j, k, c, l, m)

scala> val intl= List(3,2,5,4,8,0,4,1,5,76,9,0,4,3,2,24,45,657)
intl: List[Int] = List(3, 2, 5, 4, 8, 0, 4, 1, 5, 76, 9, 0, 4, 3, 2, 24, 45, 657)

scala> list zip intl
res0: List[(Char, Int)] = List((a,3), (b,2), (c,5), (c,4), (c,8), (d,0), (e,4), (f,1), (g,5), (h,76), (c,9), (j,0), (k,4), (c,3), (l,2), (m,24))

scala> (list zip intl) unzip
res1: (List[Char], List[Int]) = (List(a, b, c, c, c, d, e, f, g, h, c, j, k, c, l, m),List(3, 2, 5, 4, 8, 0, 4, 1, 5, 76, 9, 0, 4, 3, 2, 24))

scala>  list updated(1,'c')
res2: List[Char] = List(a, c, c, c, c, d, e, f, g, h, c, j, k, c, l, m)

scala> list view(3,8)
res3: scala.collection.SeqView[Char,List[Char]] = SeqViewS(...)

scala> list zipAll(intl,"*","-1")
res4: List[(Any, Any)] = List((a,3), (b,2), (c,5), (c,4), (c,8), (d,0), (e,4), (f,1), (g,5), (h,76), (c,9), (j,0), (k,4), (c,3), (l,2), (m,24), (*,45), (*,657))


After such a marathon series, it is finished!



Authored by Win Myo Htet

Wednesday, January 4, 2012

Learning Scala : Reading the exotic and essential List API scaladoc 13

Authored by Win Myo Htet



The functions are quite easy and are groups by their directional counterpart. indeOf* return the first index of the element in the List if it is found otherwise -1. Then, the search from the last to head of the element is invoked by lastIndexOf*.
def indexOf (elem: A, from: Int): Int
[use case] Finds index of first occurrence of some value in this list after or at some start index.
def indexOf [B >: A] (elem: B, from: Int): Int
Finds index of first occurrence of some value in this list after or at some start index.
def indexOf (elem: A): Int
[use case] Finds index of first occurrence of some value in this list.
def indexOf [B >: A] (elem: B): Int
Finds index of first occurrence of some value in this list.

def lastIndexOf (elem: A, end: Int): Int
[use case] Finds index of last occurrence of some value in this list before or at a given end index.
def lastIndexOf [B >: A] (elem: B, end: Int): Int
Finds index of last occurrence of some value in this list before or at a given end index.
def lastIndexOf (elem: A): Int
[use case] Finds index of last occurrence of some value in this list.
def lastIndexOf [B >: A] (elem: B): Int
Finds index of last occurrence of some value in this list.

def indexOfSlice [B >: A] (that: Seq[B], from: Int): Int
def indexOfSlice [B >: A] (that: GenSeq[B], from: Int): Int
Finds first index after or at a start index where this list contains a given sequence as a slice.
def indexOfSlice [B >: A] (that: Seq[B]): Int
def indexOfSlice [B >: A] (that: GenSeq[B]): Int
Finds first index where this list contains a given sequence as a slice.

def lastIndexOfSlice [B >: A] (that: Seq[B], end: Int): Int
def lastIndexOfSlice [B >: A] (that: GenSeq[B], end: Int): Int
Finds last index before or at a given end index where this list contains a given sequence as a slice.
def lastIndexOfSlice [B >: A] (that: Seq[B]): Int
def lastIndexOfSlice [B >: A] (that: GenSeq[B]): Int
Finds last index where this list contains a given sequence as a slice.

def indexWhere (p: (A) ⇒ Boolean, from: Int): Int
Finds index of the first element satisfying some predicate after or at some start index.
def indexWhere (p: (A) ⇒ Boolean): Int
Finds index of first element satisfying some predicate.
def indices : Range
Produces the range of all indices of this sequence.

def lastIndexWhere (p: (A) ⇒ Boolean, end: Int): Int
Finds index of last element satisfying some predicate before or at given end index.
def lastIndexWhere (p: (A) ⇒ Boolean): Int
Finds index of last element satisfying some predicate.

scala> val charl=(for ( ch <- 'a' to 'z') yield ch) toList
charl: List[Char] = List(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z)

scala> val list = List('a','b','c','c','c','d','e','f','g','h','c','j','k','c','l','m')
list: List[Char] = List(a, b, c, c, c, d, e, f, g, h, c, j, k, c, l, m)

scala> list indexOf 'c'
res0: Int = 2

scala> list indexOf('c',8)
res1: Int = 10

scala> list lastIndexOf('c')
res2: Int = 13

scala> list lastIndexOf('c',8)
res3: Int = 4

scala> list indexOfSlice(List('c','d','e'))
res4: Int = 4

scala> list indexOfSlice(List('c','d','e'),8)
res5: Int = -1

scala> list indexOfSlice(List('c','d','e'),2)
res6: Int = 4

scala> list lastIndexOfSlice(List('c','d','e'))
res7: Int = 4

scala> list lastIndexOfSlice(List('c','d','e'),2)
res8: Int = -1

scala> list lastIndexOfSlice(List('c','d','e'),6)
res9: Int = 4

scala> list indexWhere{ x => x == 'c'}
res10: Int = 2

scala> list indexWhere({ x => x == 'c'},8)
res11: Int = 10

scala> list lastIndexWhere({ x => x == 'c'},8)
res12: Int = 4

scala> list lastIndexWhere({ x => x == 'c'})
res13: Int = 13



intersect and union come from Math's set theory of intersect and union.
def intersect [B >: A] (that: Seq[B]): List[A]
def intersect (that: Seq[A]): List[A]
[use case] Computes the multiset intersection between this list and another sequence.
def intersect [B >: A] (that: GenSeq[B]): List[A]
Computes the multiset intersection between this list and another sequence.

def union (that: Seq[A]): List[A]
[use case] Produces a new sequence which contains all elements of this list and also all elements of a given sequence.
def union [B >: A, That] (that: GenSeq[B])(implicit bf: CanBuildFrom[List[A], B, That]): That
Produces a new sequence which contains all elements of this list and also all elements of a given sequence.
def union [B >: A, That] (that: Seq[B])(implicit bf: CanBuildFrom[List[A], B, That]): That

scala> list union charl
res26: List[Char] = List(a, b, c, c, c, d, e, f, g, h, c, j, k, c, l, m, a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z)

scala> list intersect charl
res27: List[Char] = List(a, b, c, d, e, f, g, h, j, k, l, m)


Here are the rest of the 'I' functions
def indices : Range
Produces the range of all indices of this sequence.
def isDefinedAt (x: Int): Boolean
Tests whether this list contains given index.
def isTraversableAgain : Boolean
Tests whether this list can be repeatedly traversed.
def iterator : Iterator[A]
Creates a new iterator over all elements contained in this iterable object.
Let us add a few more functions to finish off the 'L' functions.

def length : Int
The length of the list.
def lengthCompare (len: Int): Int
Compares the length of this list to a test value.

scala> list indices
res14: scala.collection.immutable.Range = Range(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15)

scala> list length
res15: Int = 16

scala> list lengthCompare 16
res16: Int = 0

scala> list lengthCompare 13
res17: Int = 1

scala> list lengthCompare 19
res18: Int = -3

scala> list isDefinedAt 19
res19: Boolean = false

scala> list isDefinedAt 14
res20: Boolean = true

scala> for (ch <- list iterator) println(ch)
a
b
c
c
c
d
e
f
g
h
c
j
k
c
l
m


Note lengthCompare function for 13(lesser than 16) does not return -3 but 1 while  lengthCompare function for 13(greater than 16) return -3. isTraversableAgain will always return for the List collection since the method inherited from here is final. More of it on SO.


Authored by Win Myo Htet

Tuesday, January 3, 2012

Learning Scala : Reading the exotic and essential List API scaladoc 12

Authored by Win Myo Htet



def genericBuilder [B] : Builder[B, List[B]]
The generic builder that builds instances of List at arbitrary element types.

def groupBy [K] (f: (A) ⇒ K): Map[K, List[A]]
Partitions this list into a map of lists according to some discriminator function.
def partition (p: (A) ⇒ Boolean): (List[A], List[A])
Partitions this list in two lists according to a predicate.

def grouped (size: Int): Iterator[List[A]]
Partitions elements in fixed size lists.
def sliding [B >: A] (size: Int): Iterator[List[A]]
Groups elements in fixed size blocks by passing a "sliding window" over them (as opposed to partitioning them, as is done in grouped.
def sliding [B >: A] (size: Int, step: Int): Iterator[List[A]]
Sorts this List according to the Ordering which results from transforming an implicitly given Ordering with a transformation function.

def hasDefiniteSize : Boolean
Tests whether this list is known to have a finite size.
def hashCode (): Int
Hashcodes for List produce a value from the hashcodes of all the elements of the list.
genericBuilder return a Builder, through which we can create the same collection type, in our case List(you might want to look up a similar function, companion, covered here.) In contrast with companion function is that you have to call function result to get the desired collection(List) type from the (List)buffer.
groupBy return the-function-defined-partition of the List as a value and it is mapped to the key. We demonstrate this by partitioning the List in terms of the modulo of 3. Lists of Odd and Even partitioning is considered for the demonstration but groupBy is capable of partitioning more than two Lists unlike the following function, thus the modulo of 3 example is used.
The function partition returns two partitions, which either satisfies the predicate or not. We have a tuple of two resulting Lists: Odd List and Even List.
grouped return iterator to get a List of n elements.
sliding is better described in the code snippet.
hasDefiniteSize is to differentiate collection, like Stream, which has infinite size, and other collection, which does not have infinite size. List does not have infinite size. hashCode return hashCode.
scala> val list = (for (i <- 1 to 11) yield i) toList
list: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11)

scala> val bldr = list.genericBuilder[Int] += (5,6,7)
bldr: scala.collection.mutable.Builder[Int,List[Int]] = ListBuffer(5, 6, 7)

scala> bldr.result
res0: List[Int] = List(5, 6, 7)

scala> list.genericBuilder[String] += ("a","b","c")
res1: scala.collection.mutable.Builder[String,List[String]] = ListBuffer(a, b, c)

scala> list groupBy { case x:Int if x % 3 == 0 => "0"; case x:Int if x % 3 == 1 => "1" ; case x:Int if x % 3 == 2 => "2"}
res2: scala.collection.immutable.Map[java.lang.String,List[Int]] = Map(0 -> List(3, 6, 9), 1 -> List(1, 4, 7, 10), 2 -> List(2, 5, 8, 11))

scala> list partition ( x => x % 2 == 0)
res3: (List[Int], List[Int]) = (List(2, 4, 6, 8, 10),List(1, 3, 5, 7, 9, 11))

scala> for ( x <- list grouped 3) println(x)
List(1, 2, 3)
List(4, 5, 6)
List(7, 8, 9)
List(10, 11)

scala> for ( x <- list sliding 3) println(x)
List(1, 2, 3)
List(2, 3, 4)
List(3, 4, 5)
List(4, 5, 6)
List(5, 6, 7)
List(6, 7, 8)
List(7, 8, 9)
List(8, 9, 10)
List(9, 10, 11)

for (x <- list.sliding(4,2)) println(x)
List(1, 2, 3, 4)
List(3, 4, 5, 6)
List(5, 6, 7, 8)
List(7, 8, 9, 10)
List(9, 10, 11)

scala> list hasDefiniteSize
res6: Boolean = true

scala> list hashCode
res7: Int = -1287208638


def head : A
Selects the first element of this list.
def headOption : Option[A]
Optionally selects the first element.
def last : A
Selects the last element.
def lastOption : Option[A]
Optionally selects the last element.

def tail : List[A]
Selects all elements except the first.
def tails : Iterator[List[A]]
Iterates over the tails of this list.
def init : List[A]
Selects all elements except the last.
def inits : Iterator[List[A]]
Iterates over the inits of this list.

def isEmpty : Boolean
Tests whether the list is empty.
def nonEmpty : Boolean
Tests whether the list is not empty.
We know head and tail early when we start reading about Scala. Here we have brought their relatives together along with its counterpart family of last(head) and init(tail). isEmpty or noEmpty? These two methods serve the same purpose. The reason for two functions for a single purpose is for self-documenting. One can see that in comment of TraversableOnce source at line 62.

scala> list head
res8: Int = 1

scala> list headOption
res9: Option[Int] = Some(1)

scala> list last
res10: Int = 11

scala> list lastOption
res11: Option[Int] = Some(11)

scala>  list tail
res12: List[Int] = List(2, 3, 4, 5, 6, 7, 8, 9, 10, 11)

scala> for (x <- list tails) println(x)
List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11)
List(2, 3, 4, 5, 6, 7, 8, 9, 10, 11)
List(3, 4, 5, 6, 7, 8, 9, 10, 11)
List(4, 5, 6, 7, 8, 9, 10, 11)
List(5, 6, 7, 8, 9, 10, 11)
List(6, 7, 8, 9, 10, 11)
List(7, 8, 9, 10, 11)
List(8, 9, 10, 11)
List(9, 10, 11)
List(10, 11)
List(11)
List()

scala> list init
res14: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

scala> for (x <- list inits) println(x)
List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11)
List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
List(1, 2, 3, 4, 5, 6, 7, 8, 9)
List(1, 2, 3, 4, 5, 6, 7, 8)
List(1, 2, 3, 4, 5, 6, 7)
List(1, 2, 3, 4, 5, 6)
List(1, 2, 3, 4, 5)
List(1, 2, 3, 4)
List(1, 2, 3)
List(1, 2)
List(1)
List()

scala> list isEmpty
res16: Boolean = false

scala> list nonEmpty
res17: Boolean = true



Authored by Win Myo Htet

Sunday, January 1, 2012

Learning Scala : Reading the exotic and essential List API scaladoc 11

Authored by Win Myo Htet



Our current logical grouping this time includes flatMap, flatten, map and mapConserve.
def flatMap [B] (f: (A) ⇒ GenTraversableOnce[B]): List[B]
[use case] Builds a new collection by applying a function to all elements of this list and concatenating the results.
def flatMap [B, That] (f: (A) ⇒ GenTraversableOnce[B])(implicit bf: CanBuildFrom[List[A], B, That]): That
Builds a new collection by applying a function to all elements of this list and concatenating the results.
def flatten [B] : List[B]
[use case] Converts this list of traversable collections into a list in which all element collections are concatenated.
def flatten [B] (implicit asTraversable: (A) ⇒ TraversableOnce[B]): Traversable[B]
Converts this list of traversable collections into a list in which all element collections are concatenated.
def map [B] (f: (A) ⇒ B): List[B]
[use case] Builds a new collection by applying a function to all elements of this list.
def map [B, That] (f: (A) ⇒ B)(implicit bf: CanBuildFrom[List[A], B, That]): That
Builds a new collection by applying a function to all elements of this list.
def mapConserve[A <: AnyRef](xs: List[A])(f: A => A): List[A]
[use case] Builds a new list by applying a function to all elements of this list.
def mapConserve [B >: A <: AnyRef] (f: (A) ⇒ B): List[B]
Builds a new list by applying a function to all elements of this list.

We create some vals. The first one is List[Option[Int]] with None included, then standard List of Int and List of Lists. We use flatten to get the List with value, which is unwrapped from Option. (the new List will not have element represented for None.) flatten can also be used to unwrapped elements from inner Lists of a List, which has Lists as elements.
scala>  val optionl= None::(for(i <- 1 to 9) yield Option(i)).toList
optionl: List[Option[Int]] = List(None, Some(1), Some(2), Some(3), Some(4), Some(5), Some(6), Some(7), Some(8), Some(9))

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

scala> val lol = optionl::list::List(11,12,13,14,15,16)::Nil
lol: List[List[Any]] = List(List(None, Some(1), Some(2), Some(3), Some(4), Some(5), Some(6), Some(7), Some(8), Some(9)), List(1, 2, 3, 4, 5, 6, 7, 8, 9), List(11, 12, 13, 14, 15, 16))

scala> for( l <- lol) println(l)
List(None, Some(1), Some(2), Some(3), Some(4), Some(5), Some(6), Some(7), Some(8), Some(9))
List(1, 2, 3, 4, 5, 6, 7, 8, 9)
List(11, 12, 13, 14, 15, 16)

scala> optionl flatten
res1: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9)

scala> lol flatten
res2: List[Any] = List(None, Some(1), Some(2), Some(3), Some(4), Some(5), Some(6), Some(7), Some(8), Some(9), 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14, 15, 16)

We will continue using vals from above. For simplicity sake, we will say that flatMap also operates on List of Lists. Using a predefined function identity, which simply return the same element, from predefwe can use flatMap to be like flatten. However map operates on non List elements. We combine the functions to get the simple List[Int].
scala> lol flatMap identity
res3: List[Any] = List(None, Some(1), Some(2), Some(3), Some(4), Some(5), Some(6), Some(7), Some(8), Some(9), 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14, 15, 16)

scala> lol flatMap identity map{case Some(x) => x; case None => 0;case x => x}
res4: List[Any] = List(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14, 15, 16)

scala> val r=lol flatMap identity map{case Some(x) => x; case None => 0;case x => x} map {case x:Int => x}
r: List[Int] = List(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14, 15, 16)

mapConserve is similar to map but the requirement is that mapConserve can only be operated on subtype of AnyRef. mapConserve also has performance advantage on map.
scala> val mcl=List("This","is","an","example","to","use","mapConverse")
mcl: List[java.lang.String] = List(This, is, an, example, to, use, mapConverse)

scala> mcl map (x => x.toUpperCase)
res5: List[java.lang.String] = List(THIS, IS, AN, EXAMPLE, TO, USE, MAPCONVERSE)

scala>  mcl mapConserve (x => x.toUpperCase)
res6: List[java.lang.String] = List(THIS, IS, AN, EXAMPLE, TO, USE, MAPCONVERSE)

scala> val optionr = r map {x => Option(x) }
optionr: List[Option[Int]] = List(Some(0), Some(1), Some(2), Some(3), Some(4), Some(5), Some(6), Some(7), Some(8), Some(9), Some(1), Some(2), Some(3), Some(4), Some(5), Some(6), Some(7), Some(8), Some(9), Some(11), Some(12), Some(13), Some(14), Some(15), Some(16))

scala> optionr mapConserve { x => Option(x.get * x.get)}
res7: List[Option[Int]] = List(Some(0), Some(1), Some(4), Some(9), Some(16), Some(25), Some(36), Some(49), Some(64), Some(81), Some(1), Some(4), Some(9), Some(16), Some(25), Some(36), Some(49), Some(64), Some(81), Some(121), Some(144), Some(169), Some(196), Some(225), Some(256))

If you would like to learn how and where some of these functions are deployed, you are in luck. You can see their usage in my first blog series, Chewy code : scala TicTacToe. Since we have covered fold and for series before, we will be addressing functions starting with genericBuilder.


Authored by Win Myo Htet

Saturday, December 31, 2011

Learning Scala : Reading the exotic and essential List API scaladoc 10

Authored by Win Myo Htet



def diff [B >: A] (that: Seq[B]): List[A]
def diff (that: Seq[A]): List[A]
[use case] Computes the multiset difference between this list and another sequence.
def diff [B >: A] (that: GenSeq[B]): List[A]
Computes the multiset difference between this list and another sequence.

def distinct : List[A]
Builds a new list from this list without any duplicate elements.

def drop (n: Int): List[A]
Selects all elements except first n ones.
def dropRight (n: Int): List[A]
Selects all elements except last n ones.
def dropWhile (p: (A) ⇒ Boolean): List[A]
Drops longest prefix of elements that satisfy a predicate.

def take (n: Int): List[A]
Selects first n elements.
def takeRight (n: Int): List[A]
Selects last n elements.
def takeWhile (p: (A) ⇒ Boolean): List[A]
Takes longest prefix of elements that satisfy a predicate.

def splitAt (n: Int): (List[A], List[A])
Splits this list into two at a given position.
diff and distinct with their description and the code snippet, which we will see below, will be good enough to understand their function. We see the take functions which compliment drop functions along with splitAt.
scala> val list=List(1,2,3,4,5,6,7,8,9,10,10,10,10)
list: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10)

scala> val evenlist=list collect {case x:Int if x%2==0=>x}
evenlist: List[Int] = List(2, 4, 6, 8, 10, 10, 10, 10)

scala> list diff evenlist
res0: List[Int] = List(1, 3, 5, 7, 9)

scala> val evenarray=evenlist toArray
evenarray: Array[Int] = Array(2, 4, 6, 8, 10, 10, 10, 10)

scala> list diff evenarray
res1: List[Int] = List(1, 3, 5, 7, 9)

scala> list distinct
res2: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

scala> list drop 10
res3: List[Int] = List(10, 10, 10)

scala> list take 10
res4: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

scala> list dropRight 3
res5: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

scala> list takeRight 3
res6: List[Int] = List(10, 10, 10)

scala> list dropWhile(x => x <= 9)
res7: List[Int] = List(10, 10, 10, 10)

scala> list takeWhile(x => x <= 9)
res8: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9)

scala> list splitAt 9
res9: (List[Int], List[Int]) = (List(1, 2, 3, 4, 5, 6, 7, 8, 9),List(10, 10, 10, 10))


startsWith has been brought to the start of the next functions list to compliment endsWith. sameElements also is here to be near equal. There also is exists and find.
def startsWith [B] (that: Seq[B], offset: Int): Boolean
def startsWith [B] (that: GenSeq[B], offset: Int): Boolean
Tests whether this list contains the given sequence at a given index.
def startsWith [B] (that: Seq[B]): Boolean
def startsWith [B] (that: GenSeq[B]): Boolean
Tests whether this list starts with the given sequence.

def endsWith [B] (that: Seq[B]): Boolean
def endsWith [B] (that: GenSeq[B]): Boolean
Tests whether this list ends with the given sequence.

def equals (that: Any): Boolean
The equals method for arbitrary sequences.

def sameElements (that: GenIterable[A]): Boolean
[use case] Checks if the other iterable collection contains the same elements in the same order as this list.
def sameElements [B >: A] (that: GenIterable[B]): Boolean
Checks if the other iterable collection contains the same elements in the same order as this list.
def sameElements [B >: A] (that: Iterable[B]): Boolean 

def exists (p: (A) ⇒ Boolean): Boolean
Tests whether a predicate holds for some of the elements of this list.

def find (p: (A) ⇒ Boolean): Option[A]
Finds the first element of the list satisfying a predicate, if any.

scala> val list=List(1,2,3,4,5,6,7,8,9,10)
list: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

scala> val startArray1=List(1,2,3) toArray
startArray1: Array[Int] = Array(1, 2, 3)

scala> val startArray2=List(0,1,2) toArray
startArray2: Array[Int] = Array(0, 1, 2)

scala> list startsWith startArray1
res0: Boolean = true

scala> list startsWith startArray2
res1: Boolean = false

scala> val endArray1=List(8,9,10) toArray
endArray1: Array[Int] = Array(8, 9, 10)

scala> val endArray2=List(8,9,0) toArray
endArray2: Array[Int] = Array(8, 9, 0)

scala> list endsWith endArray1
res2: Boolean = true

scala> list endsWith endArray2
res3: Boolean = false

scala> val array=list toArray
array: Array[Int] = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

scala> val list1 = list
list1: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

scala> list equals array
res4: Boolean = false

scala> list equals list1
res5: Boolean = true

scala> list sameElements array
res6: Boolean = true

scala> array(1)=1

scala> array(0)=2

scala> list equals array
res9: Boolean = false

scala> list exists (x=> x%2==0)
res10: Boolean = true

scala> list find (x=> x%2==0)
res11: Option[Int] = Some(2)

find return the first element, which satisfies the predicate, wrapped in Option. We will be seeing some interesting function next in flatMap and flatten.


Authored by Win Myo Htet