Showing posts with label scala. Show all posts
Showing posts with label scala. 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

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

Friday, December 30, 2011

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

Authored by Win Myo Htet


def apply (n: Int): A
Selects an element by its index in the list.

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. (or its Iterable superclass where class List is not a Seq.)
apply's description is good enough and I don't think that I have to explain it. apply can also be invoked without the function name. One can read more about it in my case class blog(companion object). canEqual is for us to override for our own class, where we can defined if we are to allow two elements to evaluate  equality. List does not override it. If we look at IterableLike (line 292), from which canEqual is inherited, it simply returns true. So, List allows to do equality for all type. collect takes Partial Functions that is constructed how we we collect the elements. collectFirst just picks the nicely-wrapped-in-Option first element from the collect. combinations can be used to create Lists that has exactly the number, which is received from  combinations's parameter, of elements from the invoking List object. companion function return a factory like class GenericCompanion from which one can create a new collection of the type like List. It is explained quite nicely at SO here.
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> list.apply(0)
res0: Int = 1

scala> list(0)
res1: Int = 1

scala> list.canEqual("anything")
res2: Boolean = true

scala> val even:PartialFunction[Int,Int]={case x:Int if x%2==0 =>x}
even: PartialFunction[Int,Int] = <function1>

scala> list collect even
res3: List[Int] = List(2, 4, 6, 8, 10)

scala> val pretty_even:PartialFunction[Int,String]={case x:Int if x%2==0 =>"-"+x+"-"}
pretty_even: PartialFunction[Int,String] = <function1>

scala> list collect pretty_even
res4: List[String] = List(-2-, -4-, -6-, -8-, -10-)

scala> list collectFirst pretty_even
res5: Option[String] = Some(-2-)

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

scala> for(x <- strList.combinations(2)) println(x)
List(a, b)
List(a, c)
List(a, d)
List(b, c)
List(b, d)
List(c, d)

scala> for(x <- strList.combinations(3)) println(x)
List(a, b, c)
List(a, b, d)
List(a, c, d)
List(b, c, d)

scala> 


We have covered compose, so let's look at the other functions start with C.
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.
contains is simple. containsSlice needs the sequenced slice as we will see that evenlist return false. There are quite a lot of copyToArray functions. copyToArray is self explanatory name but still the keyword, we usually need to look for reading such functions, is [use case]. In this case, the adequate description is provided for all the functions and we won't be going over the detail but run some code snippet. copyToBuffer needs us to use ListBuffer. The reason that it is not explicitly stated and that a lot of functions description is that the document is generated from the comments from the source code where a lot of other classes also inherit the same functions. If we go look at TraversableOnce source line 219, you will see the description for copyToBuffer. If we also look at all the sub classes, which inherit from TraversableOnce, we will see the reason why the descriptions of the functions are very generic. correponds checks if the other collections have the same elements. count checks the number of element that satisfies the predicate. In our case, it is even test.
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> list.contains(1)
res0: Boolean = true

scala> list.contains("a")
res1: Boolean = false

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

scala> val even:PartialFunction[Int,Int]={case x:Int if x%2==0 =>x}
even: PartialFunction[Int,Int] = <function1>

scala> val evenlist=list collect even
evenlist: List[Int] = List(2, 4, 6, 8, 10)

scala> list containsSlice taillist
res2: Boolean = true

scala> list containsSlice evenlist
res3: Boolean = false

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

scala> list containsSlice tailarray
res4: Boolean = true

scala> val array=new Array[Int](10)
array: Array[Int] = Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0)

scala> list.copyToArray(array,3,5)

scala> array
res6: Array[Int] = Array(0, 0, 0, 1, 2, 3, 4, 5, 0, 0)

scala> list.copyToArray(array)

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

scala> val arrayAny=new Array[Any](8)
arrayAny: Array[Any] = Array(null, null, null, null, null, null, null, null)

scala> list.copyToArray(arrayAny)

scala> arrayAny
res10: Array[Any] = Array(1, 2, 3, 4, 5, 6, 7, 8)

scala> import scala.collection.mutable.ListBuffer
import scala.collection.mutable.ListBuffer

scala> val listbuffer=new ListBuffer[Int]()
listbuffer: scala.collection.mutable.ListBuffer[Int] = ListBuffer()

scala> list.copyToBuffer(listbuffer)

scala> listbuffer
res12: scala.collection.mutable.ListBuffer[Int] = ListBuffer(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

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

scala> list.corresponds(array){(le,ae)=>le==ae}
res13: Boolean = true

scala> list.count{a => a%2==0}
res14: Int = 5
After we learn C, we learn D, right?


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