Showing posts with label programming. Show all posts
Showing posts with label programming. Show all posts

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

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

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

Thursday, December 29, 2011

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

Authored by Win Myo Htet



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 lift : (Int) ⇒ Option[A]
Turns this partial function into an plain function returning an Option result.
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.
We toggle the Ordering in the search section to By Inheritance. The above three functions are inherited from PartialFunction. We know that PartialFunction are a very powerful feature derived from the Functional Programming. Let's see how we can apply that to List.
scala> val list: List[Int] = List(1, 2, 3, 4)
list: List[Int] = List(1, 2, 3, 4)

scala> val lsqr=list.andThen(x=> x +" square is "+(x*x))
lsqr: PartialFunction[Int,java.lang.String] = <function1>

scala> lsqr(0)
res0: java.lang.String = 1 square is 1

scala> lsqr(3)
res1: java.lang.String = 4 square is 16

scala> val optionList=list lift
optionList: Int => Option[Int] = <function1>

scala> optionList(0)
res2: Option[Int] = Some(1)

scala> optionList(-1)
res3: Option[Int] = None

scala> optionList(3)
res4: Option[Int] = Some(4)

scala> optionList(4)
res5: Option[Int] = None

scala> val outOfRange:PartialFunction[Int,String]={case x=>x+" is out of Range."}
outOfRange: PartialFunction[Int,String] = <function1>

scala> val safelsqr= lsqr orElse outOfRange
safelsqr: PartialFunction[Int,java.lang.String] = <function1>

scala> safelsqr(0)
res6: java.lang.String = 1 square is 1

scala> safelsqr(-1)
res7: java.lang.String = -1 is out of Range.

scala>  safelsqr(3)
res8: java.lang.String = 4 square is 16

scala> safelsqr(4)
res9: java.lang.String = 4 is out of Range.

scala> val lcompose=list.compose((x:Int)=> x match{ case x if x< 0 => -x; case x => x})
lcompose: Int => Int = <function1>

scala>  lcompose(-1)
res10: Int = 2

We declare val list and then we define PartialFunction andThen, which return String composed of the value x and its square value. Since we are applying andThen to list the x value comes from list, which return the value for the index we give to lsqr. lift make use of the Option monad pattern(concept like Design Pattern but more powerful and abstract). The return function from lift will return value wrapped in Option. Why lift? One might wonder the choice of the word. The term comes from the Mathematics, which Functional Programming has based upon. The Option monad concept has lifted the unsafe value to the safe value wrapped in the Option, thus even when we feed the index out of range, the function does not blow up. If we feed the out of range index to our lsqr function created from andThen, it will blow up (which is ugly and thus omitted from the code demo.) That is where orElse came in. We define the Partial Function outOfRange and combine that with orElse to create a new function safelsqr. Now our safelsqr can handle out of range index without blowing up.

def compose [A] (g: (A) ⇒ Int): (A) ⇒ A
I have squeezed in compose function. The example code snippet is not a very good one(if you have a good example, please share with us). The reason is that compose mirrors andThen in a functional sense. There is a github blog from twitter on that. Let's go to apply.

Authored by Win Myo Htet

Wednesday, December 28, 2011

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

Authored by Win Myo Htet


def forall (p: (A) ⇒ Boolean): Boolean
def foreach (f: (A) ⇒ Unit): Unit
Basically forall takes predicates and return Boolean and foreach takes lambda and return nothing.
scala> val list=(for (i <- 1 to 25 if i%2 ==0) yield i) toList
list: List[Int] = List(2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24)

scala> list forall(x => x%2==0)
res0: Boolean = true

scala> list foreach println
2
4
6
8
10
12
14
16
18
20
22
24

scala> val print_pretty=(x:Int)=>{println("***"+x+"***")}
print_pretty: Int => Unit = <function1>

scala> list foreach print_pretty
***2***
***4***
***6***
***8***
***10***
***12***
***14***
***16***
***18***
***20***
***22***
***24***

scala> 


Now that we are doing some pretty printing, shall we look into some functions that can help with printing?
def addString (b: StringBuilder): StringBuilder
def addString (b: StringBuilder, sep: String): StringBuilder
def addString (b: StringBuilder, start: String, sep: String, end: String): StringBuilder
def mkString : String
def mkString (sep: String): String
def mkString (start: String, sep: String, end: String): String

scala> list
res3: List[Int] = List(2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24)

scala> list.addString(new StringBuilder(""))
res4: StringBuilder = 24681012141618202224

scala> list.addString(new StringBuilder(""),",")
res5: StringBuilder = 2,4,6,8,10,12,14,16,18,20,22,24

scala> list.addString(new StringBuilder(""),"(",",",")")
res6: StringBuilder = (2,4,6,8,10,12,14,16,18,20,22,24)

scala> list.mkString
res7: String = 24681012141618202224

scala> list.mkString(",")
res8: String = 2,4,6,8,10,12,14,16,18,20,22,24

scala> list.mkString("(",",",")")
res9: String = (2,4,6,8,10,12,14,16,18,20,22,24)
Well, that is easy. You know when I first started reading the scala code, I didn't know mkString even and have to google it.

andThen ?


Authored by Win Myo Htet

Tuesday, December 27, 2011

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

Authored by Win Myo Htet



def /:\ [A1 >: A] (z: A1)(op: (A1, A1) ⇒ A1): A1
def fold [A1 >: A] (z: A1)(op: (A1, A1) ⇒ A1): A1
def reduce [A1 >: A] (op: (A1, A1) ⇒ A1): A1
def scan [B >: A, That] (z: B)(op: (B, B) ⇒ B)(implicit cbf: CanBuildFrom[List[A], B, That]): That
def aggregate [B] (z: B)(seqop: (B, A) ⇒ B, combop: (B, B) ⇒ B): B
Since these functions are grouped together, you can say that they have some common functionality. Yes, it is their ability to do parallel processing on the List collection. fold (/:\) keeps folding, reduce:reducing and scan:scanning. Since they all are doing what they are supposed be doing(Wow, very clear!), I will be focusing on fold only and how it does parallel processing.
scala> val list=(for (i <- 1 to 25) yield i) toList
list: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25)

scala> list.fold(0){(sum,a)=>println(a+":"+sum);sum+a}
1:0
2:1
3:3
4:6
5:10
6:15
7:21
8:28
9:36
10:45
11:55
12:66
13:78
14:91
15:105
16:120
17:136
18:153
19:171
20:190
21:210
22:231
23:253
24:276
25:300
res0: Int = 325

scala> list.par.fold(0){(sum,a)=>println(a+":"+sum);sum+a}
13:0
1:0
14:0
2:0
15:14
3:2
29:13
5:1
16:0
4:0
17:16
5:4
18:33
6:9
51:42
15:6
19:0
7:0
20:19
8:7
21:39
9:15
22:60
10:24
23:82
11:34
24:105
25:129
12:45
154:93
57:21
247:78
res1: Int = 325

We create a List[Int] of 25 Int. We operate fold on it to sum up the number. If we look at the printed log, we notice that it is similar to foldLeft. The number increase in sequence. It only seems to get the optimization of foldLeft. Then, we use the function par.
def par : ParSeq[A]
Returns a parallel implementation of this collection.
With par returning the parallel collection, fold operation becomes truly parallel processing and we can see that in the printed log. It seems very easy to do parallel processing in this example because we are using the very primitive nature Int type with the sum operator + having an associative property. Well, what if we are to deal with data type that is not like Int type, then you can use aggregate and pass on the custom function for the combop lambda, which reconcile the sub-results produced by parallel processing,while seqop lambda being what you normally feed to foldLeft or reduceLeft for processing. Though the concept is easy to grasp, the implementation will be quite a challenge depending on the complexities of the underlying data. Instead of providing my own example, I will provide you the links for further reading(watching). Markus Jais has blog about the performance analysis of the aggregate's parallel processing power. Aleksandar Prokopec talks about implementation and designing for parallel processing. As usual, the question has been asked on SO and answered.

Shall we go to foreach and forall now?


Authored by Win Myo Htet

Monday, December 26, 2011

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

Authored by Win Myo Htet



def reduceLeft [B >: A] (f: (B, A) ⇒ B): B
def reduceLeftOption [B >: A] (op: (B, A) ⇒ B): Option[B]
def reduceRight [B >: A] (op: (A, B) ⇒ B): B
def reduceRightOption [B >: A] (op: (A, B) ⇒ B): Option[B]
The different between reduceLeft and foldLeft is that reduceLeft does not have seed value to start with. Because of that reduceLeft will not yield a different collection, it just reduces the List collection to a single element. We also have self documenting function reduceLeftOption, which will return the nicely wrapped result in Option.
scala> val intlist=List(1,2,3,4,5)
intlist: List[Int] = List(1, 2, 3, 4, 5)

scala> intlist.reduceLeft{(sum,a)=>sum+a}
res0: Int = 15

scala> intlist.reduceLeft{(product,a)=>product*a}
res1: Int = 120

scala> val strlist=List("a","b","c","d","e")
strlist: List[java.lang.String] = List(a, b, c, d, e)

scala> strlist.reduceLeftOption{(res,str)=>res+str}
res2: Option[java.lang.String] = Some(abcde)


We also have scanLeft which has different structure to reduceLeft. scanLeft takes an element as a seed value and return a collection of the result along with the seed value.
def scanLeft [B, That] (z: B)(op: (B, A) ⇒ B)(implicit bf: CanBuildFrom[List[A], B, That]): That
def scanRight [B, That] (z: B)(op: (A, B) ⇒ B)(implicit bf: CanBuildFrom[List[A], B, That]): That

scala> intlist
res3: List[Int] = List(1, 2, 3, 4, 5)

scala> intlist.scanLeft(0){(sum,a)=>sum+a}
res4: List[Int] = List(0, 1, 3, 6, 10, 15)

scala> intlist.scanLeft(1){(product,a)=>product*a}
res5: List[Int] = List(1, 1, 2, 6, 24, 120)

scala> strlist
res6: List[java.lang.String] = List(a, b, c, d, e)

scala> strlist.scanLeft(""){(sum,a)=>sum+a}
res7: List[java.lang.String] = List("", a, ab, abc, abcd, abcde)

You might notice that the resulting List has one extra element from seed value and you will also notice that the function signature has an extra implicit argument for CanBuildFrom, which is beyond the scope of this series.  You can safely ignore it since it is implicit argument, compiler will look for the appropriate object for you.

Since I am very fond of foldLeft, I am confused with these extra functions : reduceLeft and scanLeft, then I remember about "do while", while, for and "for each". Talking about foreach, List also have foreach and forall as collection-traversing mechanism. ... Yeh, yeh, I have been outright ignoring some very relevant functions all these times. Let's talk about fold, reduce and scan first before we get to foreach and forall.


Authored by Win Myo Htet

Friday, December 23, 2011

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

Authored by Win Myo Htet


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 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 :\ [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.
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.
If you pay attention, you will notice that I have grouped the functions by having a line separating 2 functions above and 2 below. The definitions of the functions in each group are also the same. Well, if you click on both functions: /: and :\, you will see the note stating that they are the alternative syntax of foldLeft and foldRight respectively. Is it so? If you go check out the TraversableOnce source code, from which the methods are inherited, you will see that it simply is the case at line 137 and 139 respectively.

What does foldLeft and foldRight do? They traverse recursively through the List element for data manipulation. The folding concept come from the functional programming domain. Since Scala is the hybrid of FP and OO, Scala has other OO's familiar functions for data traversing. I have collected some usage of folding vs other data traversing mechanism in the industry in this blog. I have also talked about why foldLeft is preferred over foldRight here. I really recommend you to master the folding since it is a very powerful function.

If we look into the detail description, we see that it needs an initial value z of type B and return the result of type B (Our List[+A] has element of type A). It also needs anonymous function(lambda), which is similar to java's anonymous inner class. Let's look at some code snippet.
Welcome to Scala version 2.9.1.final (Java HotSpot(TM) 64-Bit Server VM, Java 1.6.0_26).
Type in expressions to have them evaluated.
Type :help for more information.

scala>  val list=List(1,2,3,4,5)
list: List[Int] = List(1, 2, 3, 4, 5)

scala> list.foldLeft(0){(sum,a)=>sum+a}
res0: Int = 15

scala> list./:(0){(sum,a)=>sum+a}
res1: Int = 15

scala> (0 /: list){(sum,a)=>sum+a}
res2: Int = 15

scala>  list.foldRight(0){(a,sum)=>sum+a}
res3: Int = 15

scala> list.:\(0){(a,sum)=>sum+a}
res4: Int = 15

scala> (list :\ 0){(a,sum)=>sum+a}
res5: Int = 15

scala> list.foldLeft(0){(sum,a)=>println(a+":"+sum);sum+a}
1:0
2:1
3:3
4:6
5:10
res6: Int = 15

scala> list.foldRight(0){(a,sum)=>println(a+":"+sum);sum+a}
5:0
4:5
3:9
2:12
1:14
res7: Int = 15

scala> 

After I declare the val list, the following three lines are of foldLeft in different forms. foldRight usages come after that. I have included the println in the anonymous function(lambda) to show how foldLeft and foldRight traverse. Please pay attention to the position of sum and a in lambda. foldLeft and foldRight being differed in the direction and foldLeft being preferred, I will only use foldLeft for explanation here on ward. In the above code snippet, the initial value being type Int value 0 and the return of type Int and value 15; and the lambda doing the sum, the process does not seem that interesting. Let's look some more code snippet.
scala> list.foldLeft(""){(string,a)=>a+string}
res0: java.lang.String = 54321

scala> list.foldLeft("CreateString:"){(string,a)=>string+a}
res1: java.lang.String = CreateString:12345

scala> list.foldLeft(List[Int]()){(list,a)=>a*2::list}
res2: List[Int] = List(10, 8, 6, 4, 2)
Before we start with Int type 0, we get the result Int type 15. Using the same list, we have changed the initial value z to "","CreateString" and List[Int](), the results are of these respective types! Aren't you excited about such powerful function?

In the second blog of this blog series, we have talked about product and sum, along with the implicit object. If you look under the hood for them in TraversableOnce at line 188 and line 190, you will see that it is simply using foldLeft. You might also notice that I have overriden zero and one to "" in my implicit object.

When we work on product function, we get into sum function as well because they are similar in nature. Let's do the same here and look at similar functions.

Authored by Win Myo Htet

Thursday, December 22, 2011

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

Authored by Win Myo Htet




def ++ [B] (that: GenTraversableOnce[B]): List[B]
[use case] Concatenates this list with the elements of a traversable collection.
def ::: (prefix: List[A]): List[A]
[use case] Adds the elements of a given list in front of this list.
Though they look cryptic, Scala is not as bad as certain language found in the Ocean. (Scala can be abused to be that bad, if you so desire.) The ++ function can concatenates with a other traversable collection while ::: only operates on two lists adding the parameter list in front. A code snippet is worth a thousand words
scala>  val list1=List(1,2,3,4,5)
list1: List[Int] = List(1, 2, 3, 4, 5)

scala> val list2=List(6,7,8,9,10)
list2: List[Int] = List(6, 7, 8, 9, 10)

scala> val array1=Array(11,12,13,14,15)
array1: Array[Int] = Array(11, 12, 13, 14, 15)

scala> list2.++(list1)
res8: List[Int] = List(6, 7, 8, 9, 10, 1, 2, 3, 4, 5)

scala> list2.++(array1)
res9: List[Int] = List(6, 7, 8, 9, 10, 11, 12, 13, 14, 15)

scala> list2++array1
res10: List[Int] = List(6, 7, 8, 9, 10, 11, 12, 13, 14, 15)

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

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

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

scala> list2.:::(array1)
<console>:10: error: type mismatch;
 found   : Array[Int]
 required: List[?]
              list2.:::(array1)
                        ^

We concatenate list2 and list1, and list2 and array1 using ++ function. As I have said the previous blog, Scala can omit dot and () for 0 or 1 parameter. Then, there is a standard call to :::. Since any function that ends with ":" binds to the right, the following ::: execution is literally, the same as the one above. We have introduced the ++ function operating on the list1 again to compare with ::: function operating on list2. They both give the same result. Prependening function ::: is always preferred over concatenating function ++ because ::: is constant execution. The last error using ::: function is a reminder that ++ has its place dealing with other traversal collection.

What if we want to prepand other traversal collection to our list, like the last error throwing expression, instead of concatenating function ++ which deals with other traversal collection?
def ++: [B] (that: TraversableOnce[B]): List[B]
[use case]Concatenates this list with the elements 
of a traversable collection. It differs from ++ in 
that the right operand determines the type of the 
resulting collection rather than the left one.
The use case description is a bit misleading with the word concatenating and comparing with ++. The justification for comparing with ++ function might be that ++: also deals with other traversal collection. It is also concatenating to the right oprand. I am just happy that the Scala library author does not overlook these usage.
scala> val array1=Array(1,2,3,4,5)
array1: Array[Int] = Array(1, 2, 3, 4, 5)

scala> val list2=List(6,7,8,9,10)
list2: List[Int] = List(6, 7, 8, 9, 10)

scala> list2.++:(array1)
res0: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

scala> array1++:list2
res1: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)


There are also their overloaded function with lower bound and implicit parameter like product and sum we have seen in the previous blog.
def ++ [B >: A, That] (that: GenTraversableOnce[B])(implicit bf: CanBuildFrom[List[A], B, That]): That
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
def ++: [B >: A, That] (that: TraversableOnce[B])(implicit bf: CanBuildFrom[List[A], B, That]): That
def ::: [B >: A] (prefix: List[B]): List[B]
Here they are more permissible to deal with different types, thus the resulting collections are of List[Any].
scala> val listInt=List(1,2,3,4,5)
listInt: List[Int] = List(1, 2, 3, 4, 5)

scala> val listString=List("a","b","c","d")
listString: List[java.lang.String] = List(a, b, c, d)

scala> val arrayString=Array("e","f","g","h")
arrayString: Array[java.lang.String] = Array(e, f, g, h)

scala> listInt:::listString++arrayString
res0: List[Any] = List(1, 2, 3, 4, 5, a, b, c, d, e, f, g, h)

scala> arrayString++:listInt
res1: List[Any] = List(e, f, g, h, 1, 2, 3, 4, 5)

Since we have seen enough of the over loaded functions with lower bound and the implicit parameter, I won't be going over them separately for the rest of the functions.

The following functions deal with individual element prepanding/appending to the List.
def +: (elem: A): List[A]
def +: [B >: A, That] (elem: B)(implicit bf: CanBuildFrom[List[A], B, That]): That
def :+ (elem: A): List[A]
def :+ [B >: A, That] (elem: B)(implicit bf: CanBuildFrom[List[A], B, That]): That
def :: (x: A): List[A]
def :: [B >: A] (x: B): List[B]
:: and +: function prepand element to the list while :+ function append element to the list. List has two prepand function :: and +: since Scala has inherited :: function from the functional programming domain to begin with (Remember? we have seen :: as a sub class for case pattern matching in the first blog of this series.) and +: (and :+)is added later.
scala> val list=List(1,2,3,4,5)
list: List[Int] = List(1, 2, 3, 4, 5)

scala> 0+:list
res0: List[Int] = List(0, 1, 2, 3, 4, 5)

scala> -1::list
res1: List[Int] = List(-1, 1, 2, 3, 4, 5)

scala> list:+6
res2: List[Int] = List(1, 2, 3, 4, 5, 6)

scala> "a"+:list
res4: List[Any] = List(a, 1, 2, 3, 4, 5)

scala> list:+"z"
res5: List[Any] = List(1, 2, 3, 4, 5, z)

Again prepanding :: is preferred over appending. Wow, we are almost finished with the cryptic functions. I used to be intimidated browsing the List API seeing those function. Now that we have gone through it, it is clear that they are nothing to be intimidated about. It's easy ;) Let's get into a few left over cryptic functions.


Authored by Win Myo Htet