tag:blogger.com,1999:blog-84950491794940160662024-03-20T19:23:00.750-07:00AunnDroid : with "u", "n" moreWin Myo Htethttp://www.blogger.com/profile/12932751895421525726noreply@blogger.comBlogger30125tag:blogger.com,1999:blog-8495049179494016066.post-78197468472856638462012-01-06T10:38:00.000-08:002013-02-28T13:50:57.271-08:00Learning Scala : It's easy!
<b><u><i><span style="font-size: xx-small;"><div itemscope itemtype="http://data-vocabulary.org/Person">
Authored by <span itemprop="name">Win Myo Htet</span>
</div></span></i></u></b>
<br />
<br />
<br />
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.<br />
<br />
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 <a href="http://blog.aunndroid.com/2011/11/learning-scala-case-class-twitter.html" target="_blank">their usage</a>.<br />
<br />
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 <strike>poor</strike> 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.<br />
<br />
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.<br />
<br />
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.<br />
<br />
<br />
<br />
<br />
<b><u><i><span style="font-size: xx-small;"><div itemscope itemtype="http://data-vocabulary.org/Person">
Authored by <span itemprop="name">Win Myo Htet</span>
</div></span></i></u></b>
<b><u><i><span style="font-size: xx-small;"></span></i></u></b>
Win Myo Htethttp://www.blogger.com/profile/12932751895421525726noreply@blogger.com0tag:blogger.com,1999:blog-8495049179494016066.post-5902039898408975892012-01-06T10:31:00.000-08:002013-02-28T14:01:50.289-08:00Learning Scala : Scala List API with sample code snippet
<b><u><i><span style="font-size: xx-small;"><div itemscope itemtype="http://data-vocabulary.org/Person">
Authored by <span itemprop="name">Win Myo Htet</span>
</div></span></i></u></b>
<br />
<br />
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 <a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and.html" target="_blank">first</a> few blogs where some of the stuff like <a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_21.html" target="_blank">implicit</a> and <a href="http://blog.aunndroid.com/2011/12/learning-scala-upper-bound-for.html" target="_blank">lower bound</a> are covered. The later blogs assumed that these information does not need to be repeated.<b><br />
</b><br />
<br />
<b>Type Members</b><br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and.html" target="_blank">class WithFilter extends FilterMonadic[A, Repr]</a><br />
A class supporting filtered operations.<br />
<br />
<b>Abstract Value Members</b><br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_21.html" target="_blank">def productArity : Int</a><br />
The size of this product.<br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_21.html" target="_blank">def productElement (n: Int): Any</a><br />
The nth element of this product, 0-based.<br />
<br />
<b>Concrete Value Members</b><br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_22.html" target="_blank">def ++ [B] (that: GenTraversableOnce[B]): List[B]</a><br />
[use case] Concatenates this list with the elements of a traversable collection.<br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_22.html" target="_blank">def ++ [B >: A, That] (that: GenTraversableOnce[B])(implicit bf: CanBuildFrom[List[A], B, That]): That</a><br />
Concatenates this list with the elements of a traversable collection.<br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_22.html" target="_blank">def ++ [B >: A, That] (that: TraversableOnce[B])(implicit bf: CanBuildFrom[List[A], B, That]): That</a><br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_22.html" target="_blank">def ++: [B >: A, That] (that: Traversable[B])(implicit bf: CanBuildFrom[List[A], B, That]): That</a><br />
This overload exists because: for the implementation of ++: we should reuse that of ++ because many collections override it with more efficient versions.<br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_22.html" target="_blank">def ++: [B] (that: TraversableOnce[B]): List[B]</a><br />
[use case] Concatenates this list with the elements of a traversable collection.<br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_22.html" target="_blank">def ++: [B >: A, That] (that: TraversableOnce[B])(implicit bf: CanBuildFrom[List[A], B, That]): That</a><br />
Concatenates this list with the elements of a traversable collection.<br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_22.html" target="_blank">def +: (elem: A): List[A]</a><br />
[use case] Prepends an element to this list<br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_22.html" target="_blank">def +: [B >: A, That] (elem: B)(implicit bf: CanBuildFrom[List[A], B, That]): That</a><br />
Prepends an element to this list<br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_23.html" target="_blank">def /: [B] (z: B)(op: (B, A) ⇒ B): B</a><br />
Applies a binary operator to a start value and all elements of this list, going left to right.<br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_27.html" target="_blank">def /:\ [A1 >: A] (z: A1)(op: (A1, A1) ⇒ A1): A1</a><br />
A syntactic sugar for out of order folding.<br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_22.html" target="_blank">def :+ (elem: A): List[A]</a><br />
[use case] Appends an element to this list<br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_22.html" target="_blank">def :+ [B >: A, That] (elem: B)(implicit bf: CanBuildFrom[List[A], B, That]): That</a><br />
Appends an element to this list<br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_22.html" target="_blank">def :: (x: A): List[A]</a><br />
[use case] Adds an element at the beginning of this list.<br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_22.html" target="_blank">def :: [B >: A] (x: B): List[B]</a><br />
Adds an element at the beginning of this list.<br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_22.html" target="_blank">def ::: (prefix: List[A]): List[A]</a><br />
[use case] Adds the elements of a given list in front of this list.<br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_22.html" target="_blank">def ::: [B >: A] (prefix: List[B]): List[B]</a><br />
Adds the elements of a given list in front of this list.<br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_23.html" target="_blank">def :\ [B] (z: B)(op: (A, B) ⇒ B): B</a><br />
Applies a binary operator to all elements of this list and a start value, going right to left.<br />
<br />
<b>A</b><br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_28.html" target="_blank">def addString (b: StringBuilder): StringBuilder</a><br />
Appends all elements of this list to a string builder.<br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_28.html" target="_blank">def addString (b: StringBuilder, sep: String): StringBuilder</a><br />
Appends all elements of this list to a string builder using a separator string.<br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_28.html" target="_blank">def addString (b: StringBuilder, start: String, sep: String, end: String): StringBuilder</a><br />
Appends all elements of this list to a string builder using start, end, and separator strings.<br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_27.html" target="_blank">def aggregate [B] (z: B)(seqop: (B, A) ⇒ B, combop: (B, B) ⇒ B): B</a><br />
Aggregates the results of applying an operator to subsequent elements.<br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_29.html" target="_blank">def andThen [C] (k: (A) ⇒ C): PartialFunction[Int, C]</a><br />
Composes this partial function with a transformation function that gets applied to results of this partial function.<br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_30.html" target="_blank">def apply (n: Int): A</a><br />
Selects an element by its index in the list.<br />
<br />
<b>B</b><br />
<br />
<b>C</b><br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_30.html" target="_blank">def canEqual (that: Any): Boolean</a><br />
Method called from equality methods, so that user-defined subclasses can refuse to be equal to other collections of the same kind.<br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_30.html" target="_blank">def collect [B] (pf: PartialFunction[A, B]): List[B]</a><br />
[use case] Builds a new collection by applying a partial function to all elements of this list on which the function is defined.<br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_30.html" target="_blank">def collect [B, That] (pf: PartialFunction[A, B])(implicit bf: CanBuildFrom[List[A], B, That]): That</a><br />
Builds a new collection by applying a partial function to all elements of this list on which the function is defined.<br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_30.html" target="_blank">def collectFirst [B] (pf: PartialFunction[A, B]): Option[B]</a><br />
Finds the first element of the list for which the given partial function is defined, and applies the partial function to it.<br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_30.html" target="_blank">def combinations (n: Int): Iterator[List[A]]</a><br />
Iterates over combinations.<br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_30.html" target="_blank">def companion : GenericCompanion[List]</a><br />
The factory companion object that builds instances of class List.<br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_29.html" target="_blank">def compose [A] (g: (A) ⇒ Int): (A) ⇒ A</a><br />
Composes two instances of Function1 in a new Function1, with this function applied last.<br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_30.html" target="_blank">def contains (elem: Any): Boolean</a><br />
Tests whether this list contains a given value as an element.<br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_30.html" target="_blank">def containsSlice [B] (that: Seq[B]): Boolean</a><br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_30.html" target="_blank">def containsSlice [B] (that: GenSeq[B]): Boolean</a><br />
Tests whether this list contains a given sequence as a slice.<br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_30.html" target="_blank">def copyToArray (xs: Array[A], start: Int, len: Int): Unit</a><br />
[use case] Copies elements of this list to an array.<br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_30.html" target="_blank">def copyToArray [B >: A] (xs: Array[B], start: Int, len: Int): Unit</a><br />
Copies elements of this list to an array.<br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_30.html" target="_blank">def copyToArray (xs: Array[A]): Unit</a><br />
[use case] Copies values of this list to an array.<br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_30.html" target="_blank">def copyToArray [B >: A] (xs: Array[B]): Unit</a><br />
Copies values of this list to an array.<br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_30.html" target="_blank">def copyToArray (xs: Array[A], start: Int): Unit</a><br />
[use case] Copies values of this list to an array.<br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_30.html" target="_blank">def copyToArray [B >: A] (xs: Array[B], start: Int): Unit</a><br />
Copies values of this list to an array.<br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_30.html" target="_blank">def copyToBuffer [B >: A] (dest: Buffer[B]): Unit</a><br />
Copies all elements of this list to a buffer.<br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_30.html" target="_blank">def corresponds [B] (that: Seq[B])(p: (A, B) ⇒ Boolean): Boolean</a><br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_30.html" target="_blank">def corresponds [B] (that: GenSeq[B])(p: (A, B) ⇒ Boolean): Boolean</a><br />
Tests whether every element of this list relates to the corresponding element of another sequence by satisfying a test predicate.<br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_30.html" target="_blank">def count (p: (A) ⇒ Boolean): Int</a><br />
Counts the number of elements in the list which satisfy a predicate.<br />
<br />
<b>D</b><br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_31.html" target="_blank">def diff [B >: A] (that: Seq[B]): List[A]</a><br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_31.html" target="_blank">def diff (that: Seq[A]): List[A]</a><br />
[use case] Computes the multiset difference between this list and another sequence.<br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_31.html" target="_blank">def diff [B >: A] (that: GenSeq[B]): List[A]</a><br />
Computes the multiset difference between this list and another sequence.<br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_31.html" target="_blank">def distinct : List[A]</a><br />
Builds a new list from this list without any duplicate elements.<br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_31.html" target="_blank">def drop (n: Int): List[A]</a><br />
Selects all elements except first n ones.<br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_31.html" target="_blank">def dropRight (n: Int): List[A]</a><br />
Selects all elements except last n ones.<br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_31.html" target="_blank">def dropWhile (p: (A) ⇒ Boolean): List[A]</a><br />
Drops longest prefix of elements that satisfy a predicate.<br />
<br />
<b>E</b><br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_31.html" target="_blank">def endsWith [B] (that: Seq[B]): Boolean</a><br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_31.html" target="_blank">def endsWith [B] (that: GenSeq[B]): Boolean</a><br />
Tests whether this list ends with the given sequence.<br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_31.html" target="_blank">def equals (that: Any): Boolean</a><br />
The equals method for arbitrary sequences.<br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_31.html" target="_blank">def exists (p: (A) ⇒ Boolean): Boolean</a><br />
Tests whether a predicate holds for some of the elements of this list.<br />
<br />
<b>F</b><br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and.html" target="_blank">def filter (p: (A) ⇒ Boolean): List[A]</a><br />
Selects all elements of this list which satisfy a predicate.<br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and.html" target="_blank">def filterNot (p: (A) ⇒ Boolean): List[A]</a><br />
Selects all elements of this list which do not satisfy a predicate.<br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_31.html" target="_blank">def find (p: (A) ⇒ Boolean): Option[A]</a><br />
Finds the first element of the list satisfying a predicate, if any.<br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and.html" target="_blank">def flatMap [B] (f: (A) ⇒ GenTraversableOnce[B]): List[B]</a><br />
[use case] Builds a new collection by applying a function to all elements of this list and concatenating the results.<br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and.html" target="_blank">def flatMap [B, That] (f: (A) ⇒ GenTraversableOnce[B])(implicit bf: CanBuildFrom[List[A], B, That]): That</a><br />
Builds a new collection by applying a function to all elements of this list and concatenating the results.<br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and.html" target="_blank">def flatten [B] : List[B]</a><br />
[use case] Converts this list of traversable collections into a list in which all element collections are concatenated.<br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and.html" target="_blank">def flatten [B] (implicit asTraversable: (A) ⇒ TraversableOnce[B]): Traversable[B]</a><br />
Converts this list of traversable collections into a list in which all element collections are concatenated.<br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_27.html" target="_blank">def fold [A1 >: A] (z: A1)(op: (A1, A1) ⇒ A1): A1</a><br />
Folds the elements of this sequence using the specified associative binary operator.<br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_23.html" target="_blank">def foldLeft [B] (z: B)(f: (B, A) ⇒ B): B</a><br />
Applies a binary operator to a start value and all elements of this list, going left to right.<br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_23.html" target="_blank">def foldRight [B] (z: B)(f: (A, B) ⇒ B): B</a><br />
Applies a binary operator to all elements of this list and a start value, going right to left.<br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_28.html" target="_blank">def forall (p: (A) ⇒ Boolean): Boolean</a><br />
Tests whether a predicate holds for all elements of this list.<br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_28.html" target="_blank">def foreach (f: (A) ⇒ Unit): Unit</a><br />
[use case] Applies a function f to all elements of this list.<br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_28.html" target="_blank">def foreach [B] (f: (A) ⇒ B): Unit</a><br />
Applies a function f to all elements of this list.<br />
<br />
<b>G</b><br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_03.html" target="_blank">def genericBuilder [B] : Builder[B, List[B]]</a><br />
The generic builder that builds instances of List at arbitrary element types.<br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_03.html" target="_blank">def groupBy [K] (f: (A) ⇒ K): Map[K, List[A]]</a><br />
Partitions this list into a map of lists according to some discriminator function.<br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_03.html" target="_blank">def grouped (size: Int): Iterator[List[A]]</a><br />
Partitions elements in fixed size lists.<br />
<br />
<b>H</b><br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_03.html" target="_blank">def hasDefiniteSize : Boolean</a><br />
Tests whether this list is known to have a finite size.<br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_03.html" target="_blank">def hashCode (): Int</a><br />
Hashcodes for List produce a value from the hashcodes of all the elements of the list.<br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_03.html" target="_blank">def head : A</a><br />
Selects the first element of this list.<br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_03.html" target="_blank">def headOption : Option[A]</a><br />
Optionally selects the first element.<br />
<br />
<b>I</b><br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_04.html" target="_blank">def indexOf (elem: A, from: Int): Int</a><br />
[use case] Finds index of first occurrence of some value in this list after or at some start index.<br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_04.html" target="_blank">def indexOf [B >: A] (elem: B, from: Int): Int</a><br />
Finds index of first occurrence of some value in this list after or at some start index.<br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_04.html" target="_blank">def indexOf (elem: A): Int</a><br />
[use case] Finds index of first occurrence of some value in this list.<br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_04.html" target="_blank">def indexOf [B >: A] (elem: B): Int</a><br />
Finds index of first occurrence of some value in this list.<br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_04.html" target="_blank">def indexOfSlice [B >: A] (that: Seq[B], from: Int): Int</a><br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_04.html" target="_blank">def indexOfSlice [B >: A] (that: GenSeq[B], from: Int): Int</a><br />
Finds first index after or at a start index where this list contains a given sequence as a slice.<br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_04.html" target="_blank">def indexOfSlice [B >: A] (that: Seq[B]): Int</a><br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_04.html" target="_blank">def indexOfSlice [B >: A] (that: GenSeq[B]): Int</a><br />
Finds first index where this list contains a given sequence as a slice.<br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_04.html" target="_blank">def indexWhere (p: (A) ⇒ Boolean, from: Int): Int</a><br />
Finds index of the first element satisfying some predicate after or at some start index.<br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_04.html" target="_blank">def indexWhere (p: (A) ⇒ Boolean): Int</a><br />
Finds index of first element satisfying some predicate.<br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_04.html" target="_blank">def indices : Range</a><br />
Produces the range of all indices of this sequence.<br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_03.html" target="_blank">def init : List[A]</a><br />
Selects all elements except the last.<br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_03.html" target="_blank">def inits : Iterator[List[A]]</a><br />
Iterates over the inits of this list.<br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_04.html" target="_blank">def intersect [B >: A] (that: Seq[B]): List[A]</a><br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_04.html" target="_blank">def intersect (that: Seq[A]): List[A]</a><br />
[use case] Computes the multiset intersection between this list and another sequence.<br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_04.html" target="_blank">def intersect [B >: A] (that: GenSeq[B]): List[A]</a><br />
Computes the multiset intersection between this list and another sequence.<br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_04.html" target="_blank">def isDefinedAt (x: Int): Boolean</a><br />
Tests whether this list contains given index.<br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_03.html" target="_blank">def isEmpty : Boolean</a><br />
Tests whether the list is empty.<br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_04.html" target="_blank">def isTraversableAgain : Boolean</a><br />
Tests whether this list can be repeatedly traversed.<br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_04.html" target="_blank">def iterator : Iterator[A]</a><br />
Creates a new iterator over all elements contained in this iterable object.<br />
<br />
<b>J</b><br />
<br />
<b>K</b><br />
<br />
<b>L</b><br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_03.html" target="_blank">def last : A</a><br />
Selects the last element.<br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_04.html" target="_blank">def lastIndexOf (elem: A, end: Int): Int</a><br />
[use case] Finds index of last occurrence of some value in this list before or at a given end index.<br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_04.html" target="_blank">def lastIndexOf [B >: A] (elem: B, end: Int): Int</a><br />
Finds index of last occurrence of some value in this list before or at a given end index.<br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_04.html" target="_blank">def lastIndexOf (elem: A): Int</a><br />
[use case] Finds index of last occurrence of some value in this list.<br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_04.html" target="_blank">def lastIndexOf [B >: A] (elem: B): Int</a><br />
Finds index of last occurrence of some value in this list.<br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_04.html" target="_blank">def lastIndexOfSlice [B >: A] (that: Seq[B], end: Int): Int</a><br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_04.html" target="_blank">def lastIndexOfSlice [B >: A] (that: GenSeq[B], end: Int): Int</a><br />
Finds last index before or at a given end index where this list contains a given sequence as a slice.<br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_04.html" target="_blank">def lastIndexOfSlice [B >: A] (that: Seq[B]): Int</a><br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_04.html" target="_blank">def lastIndexOfSlice [B >: A] (that: GenSeq[B]): Int</a><br />
Finds last index where this list contains a given sequence as a slice.<br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_04.html" target="_blank">def lastIndexWhere (p: (A) ⇒ Boolean, end: Int): Int</a><br />
Finds index of last element satisfying some predicate before or at given end index.<br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_04.html" target="_blank">def lastIndexWhere (p: (A) ⇒ Boolean): Int</a><br />
Finds index of last element satisfying some predicate.<br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_03.html" target="_blank">def lastOption : Option[A]</a><br />
Optionally selects the last element.<br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_04.html" target="_blank">def length : Int</a><br />
The length of the list.<br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_04.html" target="_blank">def lengthCompare (len: Int): Int</a><br />
Compares the length of this list to a test value.<br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_29.html" target="_blank">def lift : (Int) ⇒ Option[A]</a><br />
Turns this partial function into an plain function returning an Option result.<br />
<br />
<b>M</b><br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and.html" target="_blank">def map [B] (f: (A) ⇒ B): List[B]</a><br />
[use case] Builds a new collection by applying a function to all elements of this list.<br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and.html" target="_blank">def map [B, That] (f: (A) ⇒ B)(implicit bf: CanBuildFrom[List[A], B, That]): That</a><br />
Builds a new collection by applying a function to all elements of this list.<br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and.html" target="_blank">def mapConserve (f: (A) ⇒ A): List[A]</a><br />
[use case] Builds a new list by applying a function to all elements of this list.<br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and.html" target="_blank">def mapConserve [B >: A <: AnyRef] (f: (A) ⇒ B): List[B]</a><br />
Builds a new list by applying a function to all elements of this list.<br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_05.html" target="_blank">def max : A</a><br />
[use case] Finds the largest element.<br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_05.html" target="_blank">def max [B >: A] (implicit cmp: Ordering[B]): A</a><br />
Finds the largest element.<br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_05.html" target="_blank">def maxBy [B] (f: (A) ⇒ B)(implicit cmp: Ordering[B]): A</a><br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_05.html" target="_blank">def min : A</a><br />
[use case] Finds the smallest element.<br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_05.html" target="_blank">def min [B >: A] (implicit cmp: Ordering[B]): A</a><br />
Finds the smallest element.<br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_05.html" target="_blank">def minBy [B] (f: (A) ⇒ B)(implicit cmp: Ordering[B]): A</a><br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_28.html" target="_blank">def mkString : String</a><br />
Displays all elements of this list in a string.<br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_28.html" target="_blank">def mkString (sep: String): String</a><br />
Displays all elements of this list in a string using a separator string.<br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_28.html" target="_blank">def mkString (start: String, sep: String, end: String): Stri</a>ng<br />
Displays all elements of this list in a string using start, end, and separator strings.<br />
<br />
<b>N</b><br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_03.html" target="_blank">def nonEmpty : Boolean</a><br />
Tests whether the list is not empty.<br />
<br />
<b>O</b><br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_29.html" target="_blank">def orElse [A1 <: Int, B1 >: A] (that: PartialFunction[A1, B1]): PartialFunction[A1, B1]</a><br />
Composes this partial function with a fallback partial function which gets applied where this partial function is not defined.<br />
<br />
<b>P</b><br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_05.html" target="_blank">def padTo (len: Int, elem: A): List[A]</a><br />
[use case] Appends an element value to this list until a given target length is reached.<br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_05.html" target="_blank">def padTo [B >: A, That] (len: Int, elem: B)(implicit bf: CanBuildFrom[List[A], B, That]): That</a><br />
Appends an element value to this list until a given target length is reached.<br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_27.html" target="_blank">def par : ParSeq[A]</a><br />
Returns a parallel implementation of this collection.<br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_03.html" target="_blank">def partition (p: (A) ⇒ Boolean): (List[A], List[A])</a><br />
Partitions this list in two lists according to a predicate.<br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_05.html" target="_blank">def patch [B >: A, That] (from: Int, patch: Seq[B], replaced: Int)(implicit bf: CanBuildFrom[List[A], B, That]): That</a><br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_05.html" target="_blank">def patch (from: Int, that: GenSeq[A], replaced: Int): List[A]</a><br />
[use case] Produces a new list where a slice of elements in this list is replaced by another sequence.<br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_05.html" target="_blank">def patch [B >: A, That] (from: Int, patch: GenSeq[B], replaced: Int)(implicit bf: CanBuildFrom[List[A], B, That]): That</a><br />
Produces a new list where a slice of elements in this list is replaced by another sequence.<br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_05.html" target="_blank">def permutations : Iterator[List[A]]</a><br />
Iterates over distinct permutations.<br />
def prefixLength (p: (A) ⇒ Boolean): Int<br />
Returns the length of the longest prefix whose elements all satisfy some predicate.<br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_21.html" target="_blank">def product : A</a><br />
[use case] Multiplies up the elements of this collection.<br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_21.html" target="_blank">def product [B >: A] (implicit num: Numeric[B]): B</a><br />
Multiplies up the elements of this collection.<br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_21.html" target="_blank">def productIterator : Iterator[Any]</a><br />
An iterator over all the elements of this product.<br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_21.html" target="_blank">def productPrefix : String</a><br />
A string used in the toString methods of derived classes.<br />
<br />
<b>Q</b><br />
<br />
<b>R</b><br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_27.html" target="_blank">def reduce [A1 >: A] (op: (A1, A1) ⇒ A1): A1</a><br />
Reduces the elements of this sequence using the specified associative binary operator.<br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_26.html" target="_blank">def reduceLeft [B >: A] (f: (B, A) ⇒ B): B</a><br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_26.html" target="_blank">def reduceLeftOption [B >: A] (op: (B, A) ⇒ B): Option[B]</a><br />
Optionally applies a binary operator to all elements of this list, going left to right.<br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_26.html" target="_blank">def reduceOption [A1 >: A] (op: (A1, A1) ⇒ A1): Option[A1]</a><br />
Optionally reduces the elements of this sequence using the specified associative binary operator.<br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_26.html" target="_blank">def reduceRight [B >: A] (op: (A, B) ⇒ B): B</a><br />
Applies a binary operator to all elements of this list, going right to left.<br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_26.html" target="_blank">def reduceRightOption [B >: A] (op: (A, B) ⇒ B): Option[B]</a><br />
Optionally applies a binary operator to all elements of this list, going right to left.<br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_05.html" target="_blank">def repr : List[A]</a><br />
The collection of type list underlying this TraversableLike object.<br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_05.html" target="_blank">def reverse : List[A]</a><br />
Returns new list wih elements in reversed order.<br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_05.html" target="_blank">def reverseIterator : Iterator[A]</a><br />
An iterator yielding elements in reversed order.<br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_05.html" target="_blank">def reverseMap [B] (f: (A) ⇒ B): List[B]</a><br />
[use case] Builds a new collection by applying a function to all elements of this list and collecting the results in reversed order.<br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_05.html" target="_blank">def reverseMap [B, That] (f: (A) ⇒ B)(implicit bf: CanBuildFrom[List[A], B, That]): That</a><br />
Builds a new collection by applying a function to all elements of this list and collecting the results in reversed order.<br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_05.html" target="_blank">def reverse_::: (prefix: List[A]): List[A]</a><br />
[use case] Adds the elements of a given list in reverse order in front of this list.<br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_05.html" target="_blank">def reverse_::: [B >: A] (prefix: List[B]): List[B]</a><br />
Adds the elements of a given list in reverse order in front of this list.<br />
<br />
<b>S</b><br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_31.html" target="_blank">def sameElements (that: GenIterable[A]): Boolean</a><br />
[use case] Checks if the other iterable collection contains the same elements in the same order as this list.<br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_31.html" target="_blank">def sameElements [B >: A] (that: GenIterable[B]): Boolean</a><br />
Checks if the other iterable collection contains the same elements in the same order as this list.<br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_31.html" target="_blank">def sameElements [B >: A] (that: Iterable[B]): Boolean</a><br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_27.html" target="_blank">def scan [B >: A, That] (z: B)(op: (B, B) ⇒ B)(implicit cbf: CanBuildFrom[List[A], B, That]): That</a><br />
Computes a prefix scan of the elements of the collection.<br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_26.html" target="_blank">def scanLeft [B, That] (z: B)(op: (B, A) ⇒ B)(implicit bf: CanBuildFrom[List[A], B, That]): That</a><br />
Produces a collection containing cummulative results of applying the operator going left to right.<br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_26.html" target="_blank">def scanRight [B, That] (z: B)(op: (A, B) ⇒ B)(implicit bf: CanBuildFrom[List[A], B, That]): That</a><br />
Produces a collection containing cummulative results of applying the operator going right to left.<br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_05.html" target="_blank">def segmentLength (p: (A) ⇒ Boolean, from: Int): Int</a><br />
Computes length of longest segment whose elements all satisfy some predicate.<br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_05.html" target="_blank">def seq : Seq[A]</a><br />
A version of this collection with all of the operations implemented sequentially (i.<br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_05.html" target="_blank">def size : Int</a><br />
The size of this list, equivalent to length.<br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_05.html" target="_blank">def slice (from: Int, until: Int): List[A]</a><br />
Selects an interval of elements.<br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_03.html" target="_blank">def sliding [B >: A] (size: Int, step: Int): Iterator[List[A]]</a><br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_03.html" target="_blank">def sliding [B >: A] (size: Int): Iterator[List[A]]</a><br />
Groups elements in fixed size blocks by passing a "sliding window" over them (as opposed to partitioning them, as is done in grouped.<br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_05.html" target="_blank">def sortBy [B] (f: (A) ⇒ B)(implicit ord: Ordering[B]): List[A]</a><br />
Sorts this List according to the Ordering which results from transforming an implicitly given Ordering with a transformation function.<br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_05.html" target="_blank">def sortWith (lt: (A, A) ⇒ Boolean): List[A]</a><br />
Sorts this list according to a comparison function.<br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_05.html" target="_blank">def sorted [B >: A] (implicit ord: Ordering[B]): List[A]</a><br />
Sorts this list according to an Ordering.<br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_05.html" target="_blank">def span (p: (A) ⇒ Boolean): (List[A], List[A])</a><br />
Splits this list into a prefix/suffix pair according to a predicate.<br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_31.html" target="_blank">def splitAt (n: Int): (List[A], List[A])</a><br />
Splits this list into two at a given position.<br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_31.html" target="_blank">def startsWith [B] (that: Seq[B], offset: Int): Boolean</a><br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_31.html" target="_blank">def startsWith [B] (that: GenSeq[B], offset: Int): Boolean</a><br />
Tests whether this list contains the given sequence at a given index.<br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_31.html" target="_blank">def startsWith [B] (that: Seq[B]): Boolean</a><br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_31.html" target="_blank">def startsWith [B] (that: GenSeq[B]): Boolean</a><br />
Tests whether this list starts with the given sequence.<br />
def stringPrefix : String<br />
Defines the prefix of this object's toString representation.<br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_21.html" target="_blank">def sum : A</a><br />
[use case] Sums up the elements of this collection.<br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_21.html" target="_blank">def sum [B >: A] (implicit num: Numeric[B]): B</a><br />
Sums up the elements of this collection.<br />
<br />
<b>T</b><br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_03.html" target="_blank">def tail : List[A]</a><br />
Selects all elements except the first.<br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_03.html" target="_blank">def tails : Iterator[List[A]]</a><br />
Iterates over the tails of this list.<br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_31.html" target="_blank">def take (n: Int): List[A]</a><br />
Selects first n elements.<br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_31.html" target="_blank">def takeRight (n: Int): List[A]</a><br />
Selects last n elements.<br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_31.html" target="_blank">def takeWhile (p: (A) ⇒ Boolean): List[A]</a><br />
Takes longest prefix of elements that satisfy a predicate.<br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_05.html" target="_blank">def toArray : Array[A]</a><br />
[use case] Converts this list to an array.<br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_05.html" target="_blank">def toArray [B >: A] (implicit arg0: ClassManifest[B]): Array[B]</a><br />
Converts this list to an array.<br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_05.html" target="_blank">def toBuffer [B >: A] : Buffer[B]</a><br />
Converts this list to a mutable buffer.<br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_05.html" target="_blank">def toIndexedSeq [B >: A] : IndexedSeq[B]</a><br />
Converts this list to an indexed sequence.<br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_05.html" target="_blank">def toIterable : Iterable[A]</a><br />
Converts this list to an iterable collection.<br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_05.html" target="_blank">def toIterator : Iterator[A]</a><br />
Returns an Iterator over the elements in this list.<br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_05.html" target="_blank">def toList : List[A]</a><br />
Converts this list to a list.<br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_05.html" target="_blank">def toMap [T, U] : Map[T, U]</a><br />
[use case] Converts this list to a map.<br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_05.html" target="_blank">def toMap [T, U] (implicit ev: <:<[A, (T, U)]): Map[T, U]</a><br />
Converts this list to a map.<br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_05.html" target="_blank">def toSeq : Seq[A]</a><br />
Converts this list to a sequence.<br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_05.html" target="_blank">def toSet [B >: A] : Set[B]</a><br />
Converts this list to a set.<br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_05.html" target="_blank">def toStream : Stream[A]</a><br />
Converts this list to a stream.<br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_05.html" target="_blank">def toString (): String</a><br />
Converts this list to a string.<br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_05.html" target="_blank">def toTraversable : Traversable[A]</a><br />
Converts this list to an unspecified Traversable.<br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_05.html" target="_blank">def transpose [B] (implicit asTraversable: (A) ⇒ TraversableOnce[B]): Traversable[Traversable[B]]</a><br />
Transposes this list of traversable collections into a list of lists.<br />
<br />
<b>U</b><br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_04.html" target="_blank">def union (that: Seq[A]): List[A]</a><br />
[use case] Produces a new sequence which contains all elements of this list and also all elements of a given sequence.<br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_04.html" target="_blank">def union [B >: A, That] (that: GenSeq[B])(implicit bf: CanBuildFrom[List[A], B, That]): That</a><br />
Produces a new sequence which contains all elements of this list and also all elements of a given sequence.<br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_04.html" target="_blank">def union [B >: A, That] (that: Seq[B])(implicit bf: CanBuildFrom[List[A], B, That]): That</a><br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_05.html" target="_blank">def unzip [A1, A2] (implicit asPair: (A) ⇒ (A1, A2)): (List[A1], List[A2])</a><br />
Converts this list of pairs into two collections of the first and second half of each pair.<br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_05.html" target="_blank">def unzip3 [A1, A2, A3] (implicit asTriple: (A) ⇒ (A1, A2, A3)): (List[A1], List[A2], List[A3])</a><br />
Converts this list of triples into three collections of the first, second, and third element of each triple.<br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_05.html" target="_blank">def updated (index: Int, elem: A): List[A]</a><br />
[use case] A copy of this list with one single replaced element.<br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_05.html" target="_blank">def updated [B >: A, That] (index: Int, elem: B)(implicit bf: CanBuildFrom[List[A], B, That]): That</a><br />
A copy of this list with one single replaced element.<br />
<br />
<b>V</b><br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_05.html" target="_blank">def view (from: Int, until: Int): SeqView[A, List[A]]</a><br />
Creates a non-strict view of a slice of this list.<br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_05.html" target="_blank">def view : SeqView[A, List[A]]</a><br />
Creates a non-strict view of this list.<br />
<br />
<b>W</b><br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and.html" target="_blank">def withFilter (p: (A) ⇒ Boolean): FilterMonadic[A, List[A]]</a><br />
Creates a non-strict filter of this list.<br />
<br />
<b>X</b><br />
<br />
<b>Y</b><br />
<br />
<b>Z</b><br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_05.html" target="_blank">def zip [A1 >: A, B, That] (that: Iterable[B])(implicit bf: CanBuildFrom[List[A], (A1, B), That]): That</a><br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_05.html" target="_blank">def zip [B] (that: GenIterable[B]): List[(A, B)]</a><br />
[use case] Returns a list formed from this list and another iterable collection by combining corresponding elements in pairs.<br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_05.html" target="_blank">def zip [A1 >: A, B, That] (that: GenIterable[B])(implicit bf: CanBuildFrom[List[A], (A1, B), That]): That</a><br />
Returns a list formed from this list and another iterable collection by combining corresponding elements in pairs.<br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_05.html" target="_blank">def zipAll [B, A1 >: A, That] (that: Iterable[B], thisElem: A1, thatElem: B)(implicit bf: CanBuildFrom[List[A], (A1, B), That]): That</a><br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_05.html" target="_blank">def zipAll [B] (that: Iterable[B], thisElem: A, thatElem: B): List[(A, B)]</a><br />
[use case] Returns a list formed from this list and another iterable collection by combining corresponding elements in pairs.<br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_05.html" target="_blank">def zipAll [B, A1 >: A, That] (that: GenIterable[B], thisElem: A1, thatElem: B)(implicit bf: CanBuildFrom[List[A], (A1, B), That]): That</a><br />
Returns a list formed from this list and another iterable collection by combining corresponding elements in pairs.<br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_05.html" target="_blank">def zipWithIndex : List[(A, Int)]</a><br />
[use case] Zips this list with its indices.<br />
<a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_05.html" target="_blank">def zipWithIndex [A1 >: A, That] (implicit bf: CanBuildFrom[List[A], (A1, Int), That]): That</a><br />
Zips this list with its indices.<br />
<br />
<br />
<br />
<b><u><i><span style="font-size: xx-small;"><div itemscope itemtype="http://data-vocabulary.org/Person">
Authored by <span itemprop="name">Win Myo Htet</span>
</div></span></i></u></b>
<b><u><i><span style="font-size: xx-small;"></span></i></u></b>
Win Myo Htethttp://www.blogger.com/profile/12932751895421525726noreply@blogger.com0tag:blogger.com,1999:blog-8495049179494016066.post-10724936663451263732012-01-05T10:34:00.000-08:002013-02-28T13:50:41.410-08:00Learning Scala : Reading the exotic and essential List API scaladoc 14
<b><u><i><span style="font-size: xx-small;"><div itemscope itemtype="http://data-vocabulary.org/Person">
Authored by <span itemprop="name">Win Myo Htet</span>
</div></span></i></u></b>
<br />
<b><u><span style="font-size: xx-small;"><br /></span></u></b>
<br />
Having gone through the needed explanation in the beginning of the series, there is little need to elaborate for most of the stuff except to show the code snippet. Let's just try to cover all the remaining functions in this blog since it has been a long series!<br />
<br />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code>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
</code></pre>
We can simply call max or min and let the Scala implicit function take care of the comparing or we can convert the element to our liking for unique comparison by using maxBy/minBy.<br />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code>def padTo (len: Int, elem: A): List[A]
[use case] Appends an element value to this list until a given target length is reached.
def padTo [B >: A, That] (len: Int, elem: B)(implicit bf: CanBuildFrom[List[A], B, That]): That
Appends an element value to this list until a given target length is reached.
def patch [B >: A, That] (from: Int, patch: Seq[B], replaced: Int)(implicit bf: CanBuildFrom[List[A], B, That]): That
def patch (from: Int, that: GenSeq[A], replaced: Int): List[A]
[use case] Produces a new list where a slice of elements in this list is replaced by another sequence.
def patch [B >: A, That] (from: Int, patch: GenSeq[B], replaced: Int)(implicit bf: CanBuildFrom[List[A], B, That]): That
Produces a new list where a slice of elements in this list is replaced by another sequence.
def permutations : Iterator[List[A]]
Iterates over distinct permutations.
</code></pre>
<br />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code>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.
</code></pre>
<br />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code>scala> val list = (for (i <- 1 to 11) yield i) toList
list: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11)
scala> list min
res0: Int = 1
scala> list max
res1: Int = 11
scala> list minBy {x => -x}
res2: Int = 11
scala> list padTo (19,11)
res3: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11)
scala> list padTo (19,'a')
res4: List[AnyVal] = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, a, a, a, a, a, a, a, a)
scala> list patch (5,List('a','b','c'),3)
res5: List[AnyVal{def getClass(): java.lang.Class[_ >: Int with Char <: AnyVal]}] = List(1, 2, 3, 4, 5, a, b, c, 9, 10, 11)
scala> list patch (5,List('a','b','c'),1)
res6: List[AnyVal{def getClass(): java.lang.Class[_ >: Int with Char <: AnyVal]}] = List(1, 2, 3, 4, 5, a, b, c, 7, 8, 9, 10, 11)
scala> list repr
res7: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11)
scala> list reverse
res8: List[Int] = List(11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1)
scala> for (i <- list reverseIterator) println(i)
11
10
9
8
7
6
5
4
3
2
1
scala> list reverseMap { x => "-"+x+"-"}
res10: List[java.lang.String] = List(-11-, -10-, -9-, -8-, -7-, -6-, -5-, -4-, -3-, -2-, -1-)
scala> list.reverse:::(List('a','b','c'))
res11: List[AnyVal{def getClass(): java.lang.Class[_ >: Char with Int <: AnyVal]}] = List(11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, a, b, c)
scala> val pl=List(1,2,3)
pl: List[Int] = List(1, 2, 3)
scala> (pl permutations) toList
res12: List[List[Int]] = List(List(1, 2, 3), List(1, 3, 2), List(2, 1, 3), List(2, 3, 1), List(3, 1, 2), List(3, 2, 1))
</code></pre>
<br />
<br />
We will start a new repl session for the rest of the functions.<br />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code>def segmentLength (p: (A) ⇒ Boolean, from: Int): Int
Computes length of longest segment whose elements all satisfy some predicate.
def seq : Seq[A]
A version of this collection with all of the operations implemented sequentially (i.
def size : Int
The size of this list, equivalent to length.
def slice (from: Int, until: Int): List[A]
Selects an interval of elements.
def sortBy [B] (f: (A) ⇒ B)(implicit ord: Ordering[B]): List[A]
Sorts this List according to the Ordering which results from transforming an implicitly given Ordering with a transformation function.
def sortWith (lt: (A, A) ⇒ Boolean): List[A]
Sorts this list according to a comparison function.
def sorted [B >: A] (implicit ord: Ordering[B]): List[A]
Sorts this list according to an Ordering.
def span (p: (A) ⇒ Boolean): (List[A], List[A])
Splits this list into a prefix/suffix pair according to a predicate.
def splitAt (n: Int): (List[A], List[A])
Splits this list into two at a given position.
</code></pre>
<br />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code>scala> val list = List('a','b','c','c','c','d','e','f','g','h','c','j','k','c','l','m')
list: List[Char] = List(a, b, c, c, c, d, e, f, g, h, c, j, k, c, l, m)
scala> list segmentLength({x => x == 'c'},0)
res0: Int = 0
scala> list segmentLength({x => x == 'c'},2)
res1: Int = 3
scala> list seq
res2: scala.collection.immutable.Seq[Char] = List(a, b, c, c, c, d, e, f, g, h, c, j, k, c, l, m)
scala> list size
res3: Int = 16
scala> list slice(3,8)
res4: List[Char] = List(c, c, d, e, f)
scala> list sorted
res5: List[Char] = List(a, b, c, c, c, c, c, d, e, f, g, h, j, k, l, m)
scala> val intl= List(3,2,5,4,8,0,4,1,5,76,9,0,4,3,2,24,45,657)
intl: List[Int] = List(3, 2, 5, 4, 8, 0, 4, 1, 5, 76, 9, 0, 4, 3, 2, 24, 45, 657)
scala> intl sorted
res6: List[Int] = List(0, 0, 1, 2, 2, 3, 3, 4, 4, 4, 5, 5, 8, 9, 24, 45, 76, 657)
scala> intl sortBy {x => -x}
res7: List[Int] = List(657, 76, 45, 24, 9, 8, 5, 5, 4, 4, 4, 3, 3, 2, 2, 1, 0, 0)
scala> intl sortWith {(x,y) => x < y}
res8: List[Int] = List(0, 0, 1, 2, 2, 3, 3, 4, 4, 4, 5, 5, 8, 9, 24, 45, 76, 657)
scala> (intl sorted) span {x => x % 2 == 0}
res9: (List[Int], List[Int]) = (List(0, 0),List(1, 2, 2, 3, 3, 4, 4, 4, 5, 5, 8, 9, 24, 45, 76, 657))
scala> (intl sorted) span {x => x < 10}
res10: (List[Int], List[Int]) = (List(0, 0, 1, 2, 2, 3, 3, 4, 4, 4, 5, 5, 8, 9),List(24, 45, 76, 657))
scala> intl splitAt 7
res11: (List[Int], List[Int]) = (List(3, 2, 5, 4, 8, 0, 4),List(1, 5, 76, 9, 0, 4, 3, 2, 24, 45, 657))
scala> val words = "The quick brown fox jumped over the lazy dog".split(' ')
words: Array[String] = Array(The, quick, brown, fox, jumped, over, the, lazy, dog)
scala> words.sortBy(x => (x.length, x.head))
res12: Array[String] = Array(The, dog, fox, the, lazy, over, brown, quick, jumped)
scala> List("Steve", "Tom", "John", "Bob").sortWith(_.compareTo(_) < 0)
res13: List[java.lang.String] = List(Bob, John, Steve, Tom)
</code></pre>
<br />
For the function <i>toMap</i>, the elements have to be <i>tuple</i> of 2 but I am lazy to create such <i>List</i> and instead, use the function <i>zip</i>, which we will see next.<br />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code>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.
</code></pre>
<br />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code>scala> val list = List('a','b','c','c','c','d','e','f','g','h','c','j','k','c','l','m')
list: List[Char] = List(a, b, c, c, c, d, e, f, g, h, c, j, k, c, l, m)
scala> val intl= List(3,2,5,4,8,0,4,1,5,76,9,0,4,3,2,24,45,657)
intl: List[Int] = List(3, 2, 5, 4, 8, 0, 4, 1, 5, 76, 9, 0, 4, 3, 2, 24, 45, 657)
scala> list toArray
res0: Array[Char] = Array(a, b, c, c, c, d, e, f, g, h, c, j, k, c, l, m)
scala> list toBuffer
res1: scala.collection.mutable.Buffer[Char] = ArrayBuffer(a, b, c, c, c, d, e, f, g, h, c, j, k, c, l, m)
scala> list toIndexedSeq
res2: scala.collection.immutable.IndexedSeq[Char] = Vector(a, b, c, c, c, d, e, f, g, h, c, j, k, c, l, m)
scala> for ( x <- list toIterable) println(x)
a
b
c
c
c
d
e
f
g
h
c
j
k
c
l
m
scala> for ( x <- list toIterator) println(x)
a
b
c
c
c
d
e
f
g
h
c
j
k
c
l
m
scala> list toList
res5: List[Char] = List(a, b, c, c, c, d, e, f, g, h, c, j, k, c, l, m)
scala> (list zip intl) toMap
res6: scala.collection.immutable.Map[Char,Int] = Map(e -> 4, j -> 0, f -> 1, a -> 3, m -> 24, b -> 2, g -> 5, l -> 2, c -> 3, h -> 76, k -> 4, d -> 0)
scala> list toSeq
res7: scala.collection.immutable.Seq[Char] = List(a, b, c, c, c, d, e, f, g, h, c, j, k, c, l, m)
scala> list toSet
res8: scala.collection.immutable.Set[Char] = Set(e, j, f, a, m, b, g, l, c, h, k, d)
scala> list toStream
res9: scala.collection.immutable.Stream[Char] = Stream(a, ?)
scala> list toString
res10: String = List(a, b, c, c, c, d, e, f, g, h, c, j, k, c, l, m)
scala> for (x <- list toTraversable) println(x)
a
b
c
c
c
d
e
f
g
h
c
j
k
c
l
m
scala> val l = List(List(1, 2, 3), List(4, 5,6), List(7, 8, 9))
l: List[List[Int]] = List(List(1, 2, 3), List(4, 5, 6), List(7, 8, 9))
scala> l.transpose
res12: List[List[Int]] = List(List(1, 4, 7), List(2, 5, 8), List(3, 6, 9))
</code></pre>
<br />
I didn't know that Scala have zip and Stream as an infinite List when I am writing "<a href="http://blog.aunndroid.com/2011/11/learning-scala-doing-scala-exercise.html" target="_blank">Learning Scala: doing Scala exercise from Haskell's example</a>". Should have gone through <i>List</i> API before!<br />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code>def unzip [A1, A2] (implicit asPair: (A) ⇒ (A1, A2)): (List[A1], List[A2])
Converts this list of pairs into two collections of the first and second half of each pair.
def unzip3 [A1, A2, A3] (implicit asTriple: (A) ⇒ (A1, A2, A3)): (List[A1], List[A2], List[A3])
Converts this list of triples into three collections of the first, second, and third element of each triple.
def updated (index: Int, elem: A): List[A]
[use case] A copy of this list with one single replaced element.
def updated [B >: A, That] (index: Int, elem: B)(implicit bf: CanBuildFrom[List[A], B, That]): That
A copy of this list with one single replaced element.
def view (from: Int, until: Int): SeqView[A, List[A]]
Creates a non-strict view of a slice of this list.
def view : SeqView[A, List[A]]
Creates a non-strict view of this list.
def zip [A1 >: A, B, That] (that: Iterable[B])(implicit bf: CanBuildFrom[List[A], (A1, B), That]): That
def zip [B] (that: GenIterable[B]): List[(A, B)]
[use case] Returns a list formed from this list and another iterable collection by combining corresponding elements in pairs.
def zip [A1 >: A, B, That] (that: GenIterable[B])(implicit bf: CanBuildFrom[List[A], (A1, B), That]): That
Returns a list formed from this list and another iterable collection by combining corresponding elements in pairs.
def zipAll [B, A1 >: A, That] (that: Iterable[B], thisElem: A1, thatElem: B)(implicit bf: CanBuildFrom[List[A], (A1, B), That]): That
def zipAll [B] (that: Iterable[B], thisElem: A, thatElem: B): List[(A, B)]
[use case] Returns a list formed from this list and another iterable collection by combining corresponding elements in pairs.
def zipAll [B, A1 >: A, That] (that: GenIterable[B], thisElem: A1, thatElem: B)(implicit bf: CanBuildFrom[List[A], (A1, B), That]): That
Returns a list formed from this list and another iterable collection by combining corresponding elements in pairs.
def zipWithIndex : List[(A, Int)]
[use case] Zips this list with its indices.
def zipWithIndex [A1 >: A, That] (implicit bf: CanBuildFrom[List[A], (A1, Int), That]): That
Zips this list with its indices.
</code></pre>
<br />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code>scala> val list = List('a','b','c','c','c','d','e','f','g','h','c','j','k','c','l','m')
list: List[Char] = List(a, b, c, c, c, d, e, f, g, h, c, j, k, c, l, m)
scala> val intl= List(3,2,5,4,8,0,4,1,5,76,9,0,4,3,2,24,45,657)
intl: List[Int] = List(3, 2, 5, 4, 8, 0, 4, 1, 5, 76, 9, 0, 4, 3, 2, 24, 45, 657)
scala> list zip intl
res0: List[(Char, Int)] = List((a,3), (b,2), (c,5), (c,4), (c,8), (d,0), (e,4), (f,1), (g,5), (h,76), (c,9), (j,0), (k,4), (c,3), (l,2), (m,24))
scala> (list zip intl) unzip
res1: (List[Char], List[Int]) = (List(a, b, c, c, c, d, e, f, g, h, c, j, k, c, l, m),List(3, 2, 5, 4, 8, 0, 4, 1, 5, 76, 9, 0, 4, 3, 2, 24))
scala> list updated(1,'c')
res2: List[Char] = List(a, c, c, c, c, d, e, f, g, h, c, j, k, c, l, m)
scala> list view(3,8)
res3: scala.collection.SeqView[Char,List[Char]] = SeqViewS(...)
scala> list zipAll(intl,"*","-1")
res4: List[(Any, Any)] = List((a,3), (b,2), (c,5), (c,4), (c,8), (d,0), (e,4), (f,1), (g,5), (h,76), (c,9), (j,0), (k,4), (c,3), (l,2), (m,24), (*,45), (*,657))
</code></pre>
<br />
After such a marathon series, it is finished!<br />
<br />
<br />
<br />
<b><u><i><span style="font-size: xx-small;"><div itemscope itemtype="http://data-vocabulary.org/Person">
Authored by <span itemprop="name">Win Myo Htet</span>
</div></span></i></u></b>
<b><u><i><span style="font-size: xx-small;"></span></i></u></b>
Win Myo Htethttp://www.blogger.com/profile/12932751895421525726noreply@blogger.com1tag:blogger.com,1999:blog-8495049179494016066.post-91207373814367437652012-01-04T10:46:00.000-08:002013-02-28T13:50:21.810-08:00Learning Scala : Reading the exotic and essential List API scaladoc 13
<b><u><i><span style="font-size: xx-small;"><div itemscope itemtype="http://data-vocabulary.org/Person">
Authored by <span itemprop="name">Win Myo Htet</span>
</div></span></i></u></b>
<br />
<br />
<br />
The functions are quite easy and are groups by their directional counterpart. <i>indeOf*</i> 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 <i>lastIndexOf*</i>.<br />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code>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.
</code></pre>
<br />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code>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
</code></pre>
<br />
<br />
<i>intersect</i> and <i>union</i> come from Math's set theory of <a href="http://en.wikipedia.org/wiki/Intersection_(set_theory)" target="_blank">intersect</a> and <a href="http://en.wikipedia.org/wiki/Union_(set_theory)" target="_blank">union</a>.<br />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code>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
</code></pre>
<br />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code>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)
</code></pre>
<br />
Here are the rest of the 'I' functions<br />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code>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.</code></pre>
Let us add a few more functions to finish off the 'L' functions.<code><br />
</code><br />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code>def length : Int
The length of the list.
def lengthCompare (len: Int): Int
Compares the length of this list to a test value.
</code></pre>
<br />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code>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
</code></pre>
<br />
Note <i>lengthCompare</i> function for 13(lesser than 16) does not return -3 but 1 while <i>lengthCompare</i> function for 13(greater than 16) return -3. <i>isTraversableAgain</i> will always return for the List collection since the method inherited from <a href="https://lampsvn.epfl.ch/trac/scala/browser/scala/tags/R_2_9_1_final/src//library/scala/collection/GenTraversableLike.scala#L64" target="_blank">here</a> is final. More of it on <a href="http://stackoverflow.com/questions/8717404/what-is-the-usage-of-istraversableagain-function-in-gentraversablelike" target="_blank">SO</a>.<br />
<br />
<br />
<b><u><i><span style="font-size: xx-small;"><div itemscope itemtype="http://data-vocabulary.org/Person">
Authored by <span itemprop="name">Win Myo Htet</span>
</div></span></i></u></b>
<b><u><i><span style="font-size: xx-small;"></span></i></u></b>
Win Myo Htethttp://www.blogger.com/profile/12932751895421525726noreply@blogger.com0tag:blogger.com,1999:blog-8495049179494016066.post-81327627287480769812012-01-03T10:23:00.000-08:002013-02-28T13:50:03.449-08:00Learning Scala : Reading the exotic and essential List API scaladoc 12
<b><u><i><span style="font-size: xx-small;"><div itemscope itemtype="http://data-vocabulary.org/Person">
Authored by <span itemprop="name">Win Myo Htet</span>
</div></span></i></u></b>
<br />
<b><u><span style="font-size: xx-small;"><br /></span></u></b>
<b><u><span style="font-size: xx-small;"><br /></span></u></b>
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code>def genericBuilder [B] : Builder[B, List[B]]
The generic builder that builds instances of List at arbitrary element types.
def groupBy [K] (f: (A) ⇒ K): Map[K, List[A]]
Partitions this list into a map of lists according to some discriminator function.
def partition (p: (A) ⇒ Boolean): (List[A], List[A])
Partitions this list in two lists according to a predicate.
def grouped (size: Int): Iterator[List[A]]
Partitions elements in fixed size lists.
def sliding [B >: A] (size: Int): Iterator[List[A]]
Groups elements in fixed size blocks by passing a "sliding window" over them (as opposed to partitioning them, as is done in grouped.
def sliding [B >: A] (size: Int, step: Int): Iterator[List[A]]
Sorts this List according to the Ordering which results from transforming an implicitly given Ordering with a transformation function.
def hasDefiniteSize : Boolean
Tests whether this list is known to have a finite size.
def hashCode (): Int
Hashcodes for List produce a value from the hashcodes of all the elements of the list.
</code></pre>
<i>genericBuilder</i> return a <i>Builder</i>, through which we can create the same collection type, in our case <i>List</i>(you might want to look up a similar function, <i>companion</i>, covered <a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_30.html" target="_blank">here</a>.) In contrast with companion function is that you have to call function <i>result</i> to get the desired collection(<i>List</i>) type from the (<i>List</i>)buffer.<br />
<i>groupBy</i> return the-function-defined-partition of the <i>List </i>as a value and it is mapped to the key. We demonstrate this by partitioning the List in terms of the modulo of 3.<i> </i><i>List</i>s of Odd and Even partitioning is considered for the demonstration but groupBy is capable of partitioning more than two <i>List</i>s unlike the following function, thus the modulo of 3 example is used.<br />
The function <i>partition</i> returns <i>two</i> partitions, which either satisfies the predicate or not. We have a tuple of two resulting <i>List</i>s: Odd List and Even List.<br />
<i>grouped</i> return iterator to get a <i>List</i> of n <i>elements</i>. <br />
<i>sliding</i> is better described in the code snippet. <br />
<i>hasDefiniteSize</i> is to differentiate collection, like <i>Stream</i>, which has infinite size, and other collection, which does not have infinite size. <i>List</i> does not have infinite size. <i>hashCode</i> return <i>hashCode</i>.<br />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code>scala> val list = (for (i <- 1 to 11) yield i) toList
list: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11)
scala> val bldr = list.genericBuilder[Int] += (5,6,7)
bldr: scala.collection.mutable.Builder[Int,List[Int]] = ListBuffer(5, 6, 7)
scala> bldr.result
res0: List[Int] = List(5, 6, 7)
scala> list.genericBuilder[String] += ("a","b","c")
res1: scala.collection.mutable.Builder[String,List[String]] = ListBuffer(a, b, c)
scala> list groupBy { case x:Int if x % 3 == 0 => "0"; case x:Int if x % 3 == 1 => "1" ; case x:Int if x % 3 == 2 => "2"}
res2: scala.collection.immutable.Map[java.lang.String,List[Int]] = Map(0 -> List(3, 6, 9), 1 -> List(1, 4, 7, 10), 2 -> List(2, 5, 8, 11))
scala> list partition ( x => x % 2 == 0)
res3: (List[Int], List[Int]) = (List(2, 4, 6, 8, 10),List(1, 3, 5, 7, 9, 11))
scala> for ( x <- list grouped 3) println(x)
List(1, 2, 3)
List(4, 5, 6)
List(7, 8, 9)
List(10, 11)
scala> for ( x <- list sliding 3) println(x)
List(1, 2, 3)
List(2, 3, 4)
List(3, 4, 5)
List(4, 5, 6)
List(5, 6, 7)
List(6, 7, 8)
List(7, 8, 9)
List(8, 9, 10)
List(9, 10, 11)
for (x <- list.sliding(4,2)) println(x)
List(1, 2, 3, 4)
List(3, 4, 5, 6)
List(5, 6, 7, 8)
List(7, 8, 9, 10)
List(9, 10, 11)
scala> list hasDefiniteSize
res6: Boolean = true
scala> list hashCode
res7: Int = -1287208638
</code></pre>
<br />
<br />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code>def head : A
Selects the first element of this list.
def headOption : Option[A]
Optionally selects the first element.
def last : A
Selects the last element.
def lastOption : Option[A]
Optionally selects the last element.
def tail : List[A]
Selects all elements except the first.
def tails : Iterator[List[A]]
Iterates over the tails of this list.
def init : List[A]
Selects all elements except the last.
def inits : Iterator[List[A]]
Iterates over the inits of this list.
def isEmpty : Boolean
Tests whether the list is empty.
def nonEmpty : Boolean
Tests whether the list is not empty.
</code></pre>
We know <i>head</i> and <i>tail</i> early when we start reading about Scala. Here we have brought their relatives together along with its counterpart family of <i>last(head)</i> and <i>init(tail)</i>. <i>isEmpty</i> or <i>noEmpty</i>? These two methods serve the same purpose. The reason for two functions for a single purpose is for self-documenting. One can see that in comment of <a href="http://www.scala-lang.org/api/current/scala/collection/TraversableOnce.html" target="_blank">TraversableOnce source</a> at line 62.<br />
<br />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code>scala> list head
res8: Int = 1
scala> list headOption
res9: Option[Int] = Some(1)
scala> list last
res10: Int = 11
scala> list lastOption
res11: Option[Int] = Some(11)
scala> list tail
res12: List[Int] = List(2, 3, 4, 5, 6, 7, 8, 9, 10, 11)
scala> for (x <- list tails) println(x)
List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11)
List(2, 3, 4, 5, 6, 7, 8, 9, 10, 11)
List(3, 4, 5, 6, 7, 8, 9, 10, 11)
List(4, 5, 6, 7, 8, 9, 10, 11)
List(5, 6, 7, 8, 9, 10, 11)
List(6, 7, 8, 9, 10, 11)
List(7, 8, 9, 10, 11)
List(8, 9, 10, 11)
List(9, 10, 11)
List(10, 11)
List(11)
List()
scala> list init
res14: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
scala> for (x <- list inits) println(x)
List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11)
List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
List(1, 2, 3, 4, 5, 6, 7, 8, 9)
List(1, 2, 3, 4, 5, 6, 7, 8)
List(1, 2, 3, 4, 5, 6, 7)
List(1, 2, 3, 4, 5, 6)
List(1, 2, 3, 4, 5)
List(1, 2, 3, 4)
List(1, 2, 3)
List(1, 2)
List(1)
List()
scala> list isEmpty
res16: Boolean = false
scala> list nonEmpty
res17: Boolean = true
</code></pre>
<br />
<br />
<b><u><i><span style="font-size: xx-small;"><div itemscope itemtype="http://data-vocabulary.org/Person">
Authored by <span itemprop="name">Win Myo Htet</span>
</div></span></i></u></b>
<b><u><i><span style="font-size: xx-small;"></span></i></u></b>
Win Myo Htethttp://www.blogger.com/profile/12932751895421525726noreply@blogger.com0tag:blogger.com,1999:blog-8495049179494016066.post-62339594212227964152012-01-01T10:37:00.000-08:002013-02-28T13:49:28.862-08:00Learning Scala : Reading the exotic and essential List API scaladoc 11
<b><u><i><span style="font-size: xx-small;"><div itemscope itemtype="http://data-vocabulary.org/Person">
Authored by <span itemprop="name">Win Myo Htet</span>
</div></span></i></u></b>
<br />
<br />
<br />
Our current logical grouping this time includes flatMap, flatten, map and mapConserve.<br />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code>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.
</code></pre>
<br />
We create some <i>val</i>s. The first one is <i>List[Option[Int]]</i> with <i>None</i> included, then standard <i>List</i> of <i>Int</i> and <i>List</i> of <i>List</i>s. We use <i>flatten</i> to get the <i>List</i> with value, which is unwrapped from <i>Option</i>. (the new <i>List</i> will not have element represented for <i>None</i>.) flatten can also be used to unwrapped elements from inner <i>List</i>s of a <i>List</i>, which has <i>List</i>s as elements.<br />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code>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)
</code></pre>
<br />
We will continue using <i>val</i>s from above. For simplicity sake, we will say that flatMap also operates on <i>List</i> of <i>List</i>s. Using a predefined function <i>identity</i>, which simply return the same element, from <i><a href="http://www.scala-lang.org/api/current/index.html#scala.Predef$" target="_blank">predef</a>, </i>we can use <i>flatMap</i> to be like <i>flatten</i>. However <i>map</i> operates on non <i>List</i> elements. We combine the functions to get the simple <i>List[Int]</i>.<br />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code>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)
</code></pre>
<br />
<i>mapConserve</i> is similar to <i>map</i> but the requirement is that <i>mapConserve</i> can only be operated on subtype of <i>AnyRef</i>. <i>mapConserve</i> also has <a href="http://stackoverflow.com/questions/8612507/scala-list-mapconserve-usage" target="_blank">performance advantage on <i>map</i></a>.<br />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code>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))
</code></pre>
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, <a href="http://blog.aunndroid.com/2011/11/chewy-code-scala-tictactoe-part-1.html" target="_blank">Chewy code : scala TicTacToe</a>. Since we have covered fold and for series before, we will be addressing functions starting with <i><a href="http://blog.aunndroid.com/2012/01/learning-scala-reading-exotic-and_03.html" target="_blank">genericBuilder</a></i>.<br />
<br />
<br />
<b><u><i><span style="font-size: xx-small;"><div itemscope itemtype="http://data-vocabulary.org/Person">
Authored by <span itemprop="name">Win Myo Htet</span>
</div></span></i></u></b>
<b><u><i><span style="font-size: xx-small;"></span></i></u></b>
Win Myo Htethttp://www.blogger.com/profile/12932751895421525726noreply@blogger.com0tag:blogger.com,1999:blog-8495049179494016066.post-4520767471886272782011-12-31T10:28:00.000-08:002013-02-28T13:49:02.539-08:00Learning Scala : Reading the exotic and essential List API scaladoc 10
<b><u><i><span style="font-size: xx-small;"><div itemscope itemtype="http://data-vocabulary.org/Person">
Authored by <span itemprop="name">Win Myo Htet</span>
</div></span></i></u></b>
<br />
<b><u><span style="font-size: xx-small;"><br /></span></u></b>
<b><u><span style="font-size: xx-small;"><br /></span></u></b>
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code>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.
</code></pre>
<i>diff</i> and <i>distinct</i> with their description and the code snippet, which we will see below, will be good enough to understand their function. We see the <i>take</i> functions which compliment <i>drop</i> functions along with <i>splitAt</i>.<br />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code>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))
</code></pre>
<br />
<i>startsWith</i> has been brought to the start of the next functions list to compliment <i>endsWith</i>. <i>sameElements</i> also is here to be near equal. There also is <i>exists</i> and <i>find</i>.<br />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code>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.
</code></pre>
<br />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code>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)
</code></pre>
<i>find</i> return the first element, which satisfies the predicate, wrapped in Option. We will be seeing some interesting function next in flatMap and flatten.<br />
<br />
<br />
<b><u><i><span style="font-size: xx-small;"><div itemscope itemtype="http://data-vocabulary.org/Person">
Authored by <span itemprop="name">Win Myo Htet</span>
</div></span></i></u></b>
<b><u><i><span style="font-size: xx-small;"></span></i></u></b>
Win Myo Htethttp://www.blogger.com/profile/12932751895421525726noreply@blogger.com0tag:blogger.com,1999:blog-8495049179494016066.post-27437161249487280712011-12-30T14:11:00.000-08:002013-02-28T13:47:56.468-08:00Learning Scala : Reading the exotic and essential List API scaladoc 9
<b><u><i><span style="font-size: xx-small;"><div itemscope itemtype="http://data-vocabulary.org/Person">
Authored by <span itemprop="name">Win Myo Htet</span>
</div></span></i></u></b>
<br />
<b><u><span style="font-size: xx-small;"><br /></span></u></b>
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code>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.)
</code></pre>
<i>apply</i>'s description is good enough and I don't think that I have to explain it. <i>apply</i> can also be invoked without the function name. One can read more about it in my <a href="http://blog.aunndroid.com/2011/11/learning-scala-case-class-twitter.html" target="_blank">case class blog(<i>companion object</i>)</a>. <i>canEqual</i> is <u>for us to override</u> for our own class, where we can defined if we are to allow two elements to evaluate equality. <i>List</i> does not override it. If we look at <a href="http://www.scala-lang.org/api/current/index.html#scala.collection.IterableLike" target="_blank">IterableLike</a> (line 292), from which <i>canEqual</i> is inherited, it simply returns true. So, <i>List</i> allows to do equality for all type. <i>collect</i> takes <i>Partial Functions</i> that is constructed how we we collect the elements. <i>collectFirst</i> just picks the nicely-wrapped-in-<i>Option</i> first element from the <i>collect</i>. <i>combinations</i> can be used to create <i>List</i>s that has exactly the number, which is received from <i>combinations</i>'s parameter, of elements from the invoking <i>List</i> object. <i>companion</i> function return a factory like class <i>GenericCompanion</i> from which one can create a new collection of the type like <i>List</i>. It is explained quite nicely at <a href="http://stackoverflow.com/questions/8568609/what-is-the-use-case-for-scala-lists-companion-function-returning-genericcompan" target="_blank">SO here</a>.<br />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code>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>
</code></pre>
<br />
We have covered <i>compose</i>, so let's look at the other functions start with C.<br />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code>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.
</code></pre>
<i>contains</i> is simple. <i>containsSlice</i> needs the sequenced slice as we will see that <i>evenlist</i> return false. There are quite a lot of <i>copyToArray</i> functions. <i>copyToArray </i>is self explanatory name but still the keyword, we usually need to look for reading such functions, is <i>[use case]</i>. 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. <i>copyToBuffer</i> needs us to use <i>ListBuffer</i>. 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 <i>TraversableOnce</i> source line 219, you will see the description for <i>copyToBuffer</i>. If we also look at all the sub classes, which inherit from <i>TraversableOnce, </i>we will see the reason why the descriptions of the functions are very generic. <i>correponds</i> checks if the other collections have the same elements. <i>count</i> checks the number of element that satisfies the predicate. In our case, it is even test.<br />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code>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
</code></pre>
After we learn C, we learn <a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_31.html" target="_blank">D</a>, right?<br />
<br />
<br />
<b><u><i><span style="font-size: xx-small;"><div itemscope itemtype="http://data-vocabulary.org/Person">
Authored by <span itemprop="name">Win Myo Htet</span>
</div></span></i></u></b>
Win Myo Htethttp://www.blogger.com/profile/12932751895421525726noreply@blogger.com0tag:blogger.com,1999:blog-8495049179494016066.post-36081508367371732232011-12-29T11:01:00.000-08:002013-02-28T13:42:46.243-08:00Learning Scala : Reading the exotic and essential List API scaladoc 8
<b><u><i><span style="font-size: xx-small;"><div itemscope itemtype="http://data-vocabulary.org/Person">
Authored by <span itemprop="name">Win Myo Htet</span>
</div></span></i></u></b>
<br />
<b><u><span style="font-size: xx-small;"><br /></span></u></b>
<b><u><span style="font-size: xx-small;"><br /></span></u></b>
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code>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.
</code></pre>
We toggle the <i>Ordering</i> in the search section to <i>By Inheritance</i>. The above three functions are inherited from <i>PartialFunction.</i> We know that <i>PartialFunction</i> are a very powerful feature derived from the Functional Programming. Let's see how we can apply that to <i>List</i>.<br />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code>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
</code></pre>
We declare <i>val list</i> and then we define <i>PartialFunction</i> <i>andThen</i>, which return <i>String</i> composed of the value <i>x</i> and its square value. Since we are applying <i>andThen</i> to <i>list</i> the <i>x</i> value comes from <i>list</i>, which return the value for the index we give to <i>lsqr</i>. <i>lift</i> make use of the <i>Option</i> <i>monad pattern</i>(concept like <i>Design Pattern</i> but more powerful and abstract). The return function from lift will return value wrapped in <i>Option</i>. Why <i>lift</i>? One might wonder the choice of the word. The term comes from the Mathematics, which Functional Programming has based upon. The <i>Option monad</i> concept has <i>lift</i>ed the unsafe value to the safe value wrapped in the <i>Option</i>, 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 <i>lsqr</i> function created from <i>andThen</i>, it will blow up (which is ugly and thus omitted from the code demo.) That is where orElse came in. We define the <i>Partial Function outOfRange</i> and combine that with <i>orElse</i> to create a new function <i>safelsqr</i>. Now our <i>safelsqr</i> can handle out of range index without blowing up.<br />
<br />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code>def compose [A] (g: (A) ⇒ Int): (A) ⇒ A
</code></pre>
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 <a href="http://twitter.github.com/scala_school/pattern-matching-and-functional-composition.html" target="_blank">that</a>. Let's go to<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_30.html" target="_blank"> apply</a>.<br />
<br />
<b><u><i><span style="font-size: xx-small;"><div itemscope itemtype="http://data-vocabulary.org/Person">
Authored by <span itemprop="name">Win Myo Htet</span>
</div></span></i></u></b>
Win Myo Htethttp://www.blogger.com/profile/12932751895421525726noreply@blogger.com0tag:blogger.com,1999:blog-8495049179494016066.post-43347499704123449552011-12-28T11:13:00.000-08:002013-02-28T13:42:00.692-08:00Learning Scala : Reading the exotic and essential List API scaladoc 7
<b><u><i><span style="font-size: xx-small;"><div itemscope itemtype="http://data-vocabulary.org/Person">
Authored by <span itemprop="name">Win Myo Htet</span>
</div></span></i></u></b>
<br />
<b><u><span style="font-size: xx-small;"><br /></span></u></b>
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code>def forall (p: (A) ⇒ Boolean): Boolean
def foreach (f: (A) ⇒ Unit): Unit
</code></pre>
Basically <i>forall</i> takes <i>predicates</i> and return <i>Boolean</i> and <i>foreach</i> takes <i>lambda</i> and return nothing.<br />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code>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>
</code></pre>
<br />
Now that we are doing some pretty printing, shall we look into some functions that can help with printing?<br />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code>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
</code></pre>
<br />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code>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)
</code></pre>
Well, that is easy. You know when I first started <a href="http://blog.aunndroid.com/2011/11/chewy-code-scala-tictactoe-part-1.html" target="_blank">reading the scala code</a>, I didn't know mkString even and have to google it.<br />
<br />
<a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_29.html" target="_blank">andThen</a> ?<br />
<br />
<br />
<b><u><i><span style="font-size: xx-small;"><div itemscope itemtype="http://data-vocabulary.org/Person">
Authored by <span itemprop="name">Win Myo Htet</span>
</div></span></i></u></b>
<b><u><i><span style="font-size: xx-small;"></span></i></u></b>
Win Myo Htethttp://www.blogger.com/profile/12932751895421525726noreply@blogger.com0tag:blogger.com,1999:blog-8495049179494016066.post-56145628928913625562011-12-27T12:02:00.000-08:002013-02-28T13:41:37.706-08:00Learning Scala : Reading the exotic and essential List API scaladoc 6
<b><u><i><span style="font-size: xx-small;"><div itemscope itemtype="http://data-vocabulary.org/Person">
Authored by <span itemprop="name">Win Myo Htet</span>
</div></span></i></u></b>
<br />
<b><u><span style="font-size: xx-small;"><br /></span></u></b>
<b><u><span style="font-size: xx-small;"><br /></span></u></b>
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code>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
</code></pre>
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. <i>fold</i> (/:\) keeps folding, <i>reduce</i>:reducing and <i>scan</i>: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.<br />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code>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
</code></pre>
We create a <i>List[Int]</i> of 25 <i>Int</i>. We operate <i>fold</i> on it to sum up the number. If we look at the printed log, we notice that it is similar to <i>foldLeft</i>. The number increase in sequence. It only seems to get the optimization of <i>foldLeft</i>. Then, we use the function <i>par</i>.<br />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code>def par : ParSeq[A]
Returns a parallel implementation of this collection.
</code></pre>
With <i>par</i> returning the parallel collection, <i>fold</i> 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 <i>Int</i> 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 <i>combop</i> lambda, which reconcile the sub-results produced by parallel processing,while <i>seqop</i> lambda being what you normally feed to <i>foldLeft</i> or <i>reduceLeft</i> 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). <a href="http://markusjais.com/scalas-parallel-collections-and-the-aggregate-method/" target="_blank">Markus Jais</a> has blog about the performance analysis of the aggregate's parallel processing power. <a href="http://www.infoq.com/news/2011/05/scala-29" target="_blank">Aleksandar Prokopec</a> talks about implementation and designing for parallel processing. As usual, the question has been asked on <a href="http://stackoverflow.com/questions/6928374/example-of-the-scala-aggregate-function" target="_blank">SO</a> and answered.<br />
<br />
Shall we go to foreach and forall now?<br />
<br />
<br />
<b><u><i><span style="font-size: xx-small;"><div itemscope itemtype="http://data-vocabulary.org/Person">
Authored by <span itemprop="name">Win Myo Htet</span>
</div></span></i></u></b>
<b><u><i><span style="font-size: xx-small;"></span></i></u></b>
Win Myo Htethttp://www.blogger.com/profile/12932751895421525726noreply@blogger.com0tag:blogger.com,1999:blog-8495049179494016066.post-64954729719877819352011-12-26T10:19:00.000-08:002013-02-28T13:41:12.557-08:00Learning Scala : Reading the exotic and essential List API scaladoc 5
<b><u><i><span style="font-size: xx-small;"><div itemscope itemtype="http://data-vocabulary.org/Person">
Authored by <span itemprop="name">Win Myo Htet</span>
</div></span></i></u></b>
<br />
<b><u><span style="font-size: xx-small;"><br /></span></u></b>
<b><u><span style="font-size: xx-small;"><br /></span></u></b>
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code>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]
</code></pre>
The different between <i>reduceLeft</i> and <i><a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_23.html" target="_blank">foldLeft</a></i> is that <i>reduceLeft</i> does not have seed value to start with. Because of that <i>reduceLeft</i> will not yield a different collection, it just <i>reduce</i>s the <i>List</i> collection to a single element. We also have self documenting function <i>reduceLeftOption</i>, which will return the nicely wrapped result in <a href="http://www.codecommit.com/blog/scala/the-option-pattern" target="_blank"><i>Option</i></a>.<br />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code>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)
</code></pre>
<br />
We also have <i>scanLeft</i> which has different structure to <i>reduceLeft</i>. scanLeft takes an element as a seed value and return a collection of the result along with the seed value.<br />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code>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
</code></pre>
<br />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code>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)
</code></pre>
You might notice that the resulting <i>List</i> has one extra element from seed value and you will also notice that the function signature has an extra <i>implicit</i> argument for <i>CanBuildFrom</i>, which is beyond the scope of this series. You can safely <a href="http://grahamhackingscala.blogspot.com/2011/01/scala-pragmatism-ignore-canbuildfrom.html" target="_blank">ignore</a> it since it is <i>implicit</i> argument, compiler will look for the appropriate object for you.<br />
<br />
Since I am very fond of foldLeft, I am confused with these extra functions : reduceLeft and scanLeft, then I remember about <i>"do while"</i>, <i>while</i>, <i>for and </i><i>"for each". </i>Talking about <i>foreach</i>, List also have <i>foreach</i> and <i>forall</i> as collection-traversing mechanism. ... Yeh, yeh, I have been outright ignoring some very relevant functions all these times. Let's talk about <a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_27.html" target="_blank">fold, reduce and scan</a> first before we get to <a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_28.html" target="_blank">foreach and forall</a>.<br />
<br />
<br />
<b><u><i><span style="font-size: xx-small;"><div itemscope itemtype="http://data-vocabulary.org/Person">
Authored by <span itemprop="name">Win Myo Htet</span>
</div></span></i></u></b>
<b><u><i><span style="font-size: xx-small;"></span></i></u></b>
Win Myo Htethttp://www.blogger.com/profile/12932751895421525726noreply@blogger.com0tag:blogger.com,1999:blog-8495049179494016066.post-66180938014463352522011-12-23T10:31:00.000-08:002013-02-28T13:40:52.513-08:00Learning Scala : Reading the exotic and essential List API scaladoc 4
<b><u><i><span style="font-size: xx-small;"><div itemscope itemtype="http://data-vocabulary.org/Person">
Authored by <span itemprop="name">Win Myo Htet</span>
</div></span></i></u></b>
<br />
<b><u><span style="font-size: xx-small;"><br /></span></u></b>
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code>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.
</code></pre>
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 <i>foldLeft</i> and <i>foldRight</i> respectively. Is it so? If you go check out the <a href="http://www.scala-lang.org/api/current/index.html#scala.collection.TraversableOnce" target="_blank">TraversableOnce</a> source code, from which the methods are inherited, you will see that it simply is the case at line 137 and 139 respectively. <br />
<br />
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 <a href="http://blog.aunndroid.com/2011/11/learning-scala-case-class-twitter.html" target="_blank">blog</a>. I have also talked about why foldLeft is preferred over foldRight <a href="http://blog.aunndroid.com/2011/11/learning-scala-recursion-and-tco-1.html" target="_blank">here</a>. I really recommend you to master the folding since it is a very powerful function.<br />
<br />
If we look into the detail description, we see that it needs an initial value <i>z</i> of type <i>B</i> and return the result of type <i>B</i> (Our <i>List[+A]</i> has element of type <i>A</i>). It also needs <i>anonymous function</i>(<i>lambda</i>), which is similar to java's <i>anonymous inner class</i>. Let's look at some code snippet.<br />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code>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>
</code></pre>
After I declare the <i>val list</i>, the following three lines are of <i>foldLeft</i> in different forms. <i>foldRight</i> usages come after that. I have included the <i>println</i> in the <i>anonymous function(lambda)</i> to show how <i>foldLeft</i> and <i>foldRight</i> traverse. Please pay attention to the position of <i>sum</i> and <i>a</i> in <i>lambda</i>. <i>foldLeft</i> and <i>foldRight</i> being differed in the direction and <i>foldLeft</i> being preferred, I will only use <i>foldLeft</i> 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.<br />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code>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)
</code></pre>
Before we start with Int type 0, we get the result Int type 15. Using the same <i>list</i>, we have changed the initial value <i>z</i> to <i>"","CreateString"</i> and <i>List[Int]()</i>, the results are of these respective types! Aren't you excited about such powerful function?<br />
<br />
In the second blog of this blog series, we have talked about <i>product</i> and <i>sum, </i>along with the <i>implicit object</i><i>.</i> If you look under the hood for them in <a href="http://www.scala-lang.org/api/current/index.html#scala.collection.TraversableOnce" target="_blank">TraversableOnce</a> at line 188 and line 190, you will see that it is simply using <i>foldLeft</i>. You might also notice that I have overriden <i>zero</i> and <i>one</i> to "" in my <i>implicit object</i>. <br />
<br />
When we work on <i>product</i> function, we get into <i>sum</i> function as well because they are similar in nature. Let's do the same here and look at <a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_26.html" target="_blank">similar functions</a>.<br />
<br />
<b><u><i><span style="font-size: xx-small;"><div itemscope itemtype="http://data-vocabulary.org/Person">
Authored by <span itemprop="name">Win Myo Htet</span>
</div></span></i></u></b>Win Myo Htethttp://www.blogger.com/profile/12932751895421525726noreply@blogger.com0tag:blogger.com,1999:blog-8495049179494016066.post-89910760272634789492011-12-22T10:27:00.000-08:002013-02-28T13:40:35.304-08:00Learning Scala : Reading the exotic and essential List API scaladoc 3
<b><u><i><span style="font-size: xx-small;"><div itemscope itemtype="http://data-vocabulary.org/Person">
Authored by <span itemprop="name">Win Myo Htet</span>
</div></span></i></u></b>
<br />
<b><u><span style="font-size: xx-small;"><br /></span></u></b>
<b><u><span style="font-size: xx-small;"><br /></span></u></b>
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code>
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.
</code></pre>
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 <i>++</i> function can concatenates with a other traversable collection while <i>:::</i> only operates on two lists adding the parameter list in front. A code snippet is worth a thousand words<br />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code>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)
^
</code></pre>
We concatenate list2 and list1, and list2 and array1 using <i>++</i> 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 <i>:::</i>. Since any function that ends with ":" binds to the right, the following <i>:::</i> execution is literally, the same as the one above. We have introduced the ++ function <u>operating on the <i>list1</i></u> again to compare with ::: function <u>operating on <i>list2</i></u>. They both give the same result. Prependening function <i>:::</i> is <i>always</i> preferred over concatenating function <i>++</i> because <i>:::</i> is constant execution. The last error using <i>:::</i> function is a reminder that ++ has its place dealing with other traversal collection.<br />
<br />
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?<br />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code>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.
</code></pre>
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.<br />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code>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)
</code></pre>
<br />
There are also their overloaded function with <i>lower bound</i> and <i>implicit parameter</i> like product and sum we have seen in the previous blog.<br />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code>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]
</code></pre>
Here they are more permissible to deal with different types, thus the resulting collections are of <i>List[Any</i>].<br />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code>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)
</code></pre>
Since we have seen enough of the over loaded functions with <i>lower bound</i> and the <i>implicit parameter</i>, I won't be going over them separately for the rest of the functions.<br />
<br />
The following functions deal with individual element prepanding/appending to the List.<br />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code>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]
</code></pre>
:: 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 <i>pattern matching</i> in the first blog of this series.) and +: (and :+)is added later.<br />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code>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)
</code></pre>
Again prepanding <i>::</i> 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 href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_23.html" target="_blank">a few left over cryptic functions</a>.<br />
<br />
<br />
<b><u><i><span style="font-size: xx-small;"><div itemscope itemtype="http://data-vocabulary.org/Person">
Authored by <span itemprop="name">Win Myo Htet</span>
</div></span></i></u></b>
<b><u><i><span style="font-size: xx-small;"></span></i></u></b>
Win Myo Htethttp://www.blogger.com/profile/12932751895421525726noreply@blogger.com0tag:blogger.com,1999:blog-8495049179494016066.post-27320525585594745092011-12-21T11:26:00.000-08:002013-02-28T13:40:16.255-08:00Learning Scala : Reading the exotic and essential List API scaladoc 2
<b><u><i><span style="font-size: xx-small;"><div itemscope itemtype="http://data-vocabulary.org/Person">
Authored by <span itemprop="name">Win Myo Htet</span>
</div></span></i></u></b>
<br />
<b><u><span style="font-size: xx-small;"><br /></span></u></b>
Before we look into <i>Abstract Value Members</i> of List API, I assume that you have refreshed the <a href="http://www.scala-lang.org/api/current/index.html#scala.collection.immutable.List" target="_blank">List API scaladoc</a> page so that the <i>Search Section</i> is back to default. There are two functions <i>productArity</i> and <i>productElement</i> under <i>Abstract Value Members</i>. In the search box, type "product" and change <i>Ordering</i> to <i>By inheritance</i>. We see that the two stated functions along with extra two functions are inherited from <i>Product</i> and there are also two other separate funtions, product from different classes. <i>Product</i> is, sort of, <i>Tuple</i>'s cousin. I have covered a bit of <i>Product</i> in my blog: <a href="http://blog.aunndroid.com/2011/11/learning-scala-case-class-twitter.html" target="_blank">Learning Scala : "case class", twitter interview question?</a> Please read up that blog to learn more about <i>Product</i>. I will still cover some of its usage here.<br />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code>
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.productArity
res0: Int = 2
scala> list.productElement(0)
res1: Any = 1
scala> list.productElement(1)
res2: Any = List(2, 3, 4, 5, 6, 7, 8, 9, 10)
scala> list.productPrefix
res3: java.lang.String = ::
</code></pre>
<i>productArity</i> talks about the number of field in the class. We have 2 fields. The first being 1 and the rest being the list. Hmmm..... Then, the <i>productPrefix</i>, which is a <i>toString</i> methods of the derived class, is <i>"::</i>". If we look at the source code at line 390, <i>::</i> class.<br />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code>final case class ::[B](private var hd: B, private[scala] var tl: List[B]) extends List[B] {
override def head : B = hd
override def tail : List[B] = tl
override def isEmpty: Boolean = false
.
.
.
</code></pre>
It all makes sense now. The first field is head and the rest is tail. It is a <i>case class</i> and you will have a sense that the very well used List's pattern matching format of <i>head::tail</i> is coming from here. Scala List API author has done the bulk of lifting(converting) for the developer ease of use of <i>head::tail</i> from <i>::(head, tail)</i>. That process is beyond the scope of this blog. <a href="http://dcsobral.blogspot.com/" target="_blank">Daniel C. Sobral</a> has talked a bit about it on <a href="http://stackoverflow.com/questions/5311653/scala-and-the-object" target="_blank">SO</a>.<br />
<br />
That leaves us with two functions: <i>product</i> and <i>product</i>.<br />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code>def product : A
def product [B >: A] (implicit num: Numeric[B]): B
</code></pre>
Generally, they both serve the same purpose: <i>Multiplies up the elements of this collection</i>. The first <i>product</i> is for number literal and does not take any parameter. Leaving out the parameter is a Scala idiomatic usage meaning that the function does not have <i>side effect</i>. The second one has restriction in a form of <a href="http://blog.aunndroid.com/2011/12/learning-scala-upper-bound-for.html" target="_blank">lower bound,<code> [B >: A]</code>,</a> and takes the <i>implicit parameter</i>.<br />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code>
scala> val numList=List(1,2,3)
numList: List[Int] = List(1, 2, 3)
scala> numList.product
res0: Int = 6
scala> numList.product()
<console>:9: error: not enough arguments for method product: (implicit num: Numeric[B])B.
Unspecified value parameter num.
numList.product()
^
scala> numList.sum
res2: Int = 6
scala> numList.sum()
<console>:9: error: not enough arguments for method sum: (implicit num: Numeric[B])B.
Unspecified value parameter num.
numList.sum()
^
scala> val stringList=List("one","two","three")
stringList: List[java.lang.String] = List(one, two, three)
scala> stringList.product
<console>:9: error: could not find implicit value for parameter num: Numeric[java.lang.String]
stringList.product
^
scala> stringList.sum
<console>:9: error: could not find implicit value for parameter num: Numeric[java.lang.String]
stringList.sum
^
scala> implicit object StringNumeric extends math.Numeric[String] {
| override def one=""
| override def zero=""
| def plus(x: String, y: String) =(x,y)match {case ("",y) =>y
| case (x,y) => x+" + "+y}
| def minus(x: String, y: String) = x+" - "+y
| def times(x: String, y: String)=(x,y)match {case ("",y) =>y
| case (x,y) => x+" * "+y}
| def negate(x: String): String ="-"+x
| def fromInt(x: Int) = x.toString
| def toInt(x: String) = -1
| def toLong(x: String) = toInt(x)
| def toFloat(x: String) = toInt(x)
| def toDouble(x: String) = toInt(x)
| def compare(x:String,y:String) = -1
| }
defined module StringNumeric
scala> stringList.product
res6: java.lang.String = one * two * three
scala> stringList.sum
res7: java.lang.String = one + two + three
</code></pre>
In the code snippet, we see the usage of the first function <i>product</i> on List with integers. Since <i>product</i> function is defined without the () to begin with, the error is thrown. However, if the function is defined as <i>product()</i>, then adding or leaving <i>() </i>won't be any issue. It is also the same for function call <i>sum</i>. When we try to apply(abuse) <i>product</i> and <i>sum</i> on <i>stringList</i>, it throws error. I have created(abused) the <i>implicit object</i> to show you the power of the Scala <i>implicit</i> feature and the <i>product</i>(and <i>sum</i>) function with <i><a href="http://www.scala-lang.org/node/114" target="_blank">implicit paramter</a></i>. Here we also leave out the parenthesis along with the parameter (which is fed from the List) when we are using the function <i>product</i>. (Scala allows to leave out the parenthesis, dot and parameter for function with one or zero parameter.)<br />
<br />
Well, we have finished reading the <i>Abstract Value Members</i> section and 6 functions from the <i>Concrete Value Members </i>section : <i>product, product, productIterator, productPrefix, sum </i>and<i> sum</i>. Let's go take a look at those cryptic functions : <a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_22.html" target="_blank">++ :+ :: :\ /:\ ...</a><br />
<br />
<br />
<b><u><i><span style="font-size: xx-small;"><div itemscope itemtype="http://data-vocabulary.org/Person">
Authored by <span itemprop="name">Win Myo Htet</span>
</div></span></i></u></b>
Win Myo Htethttp://www.blogger.com/profile/12932751895421525726noreply@blogger.com0tag:blogger.com,1999:blog-8495049179494016066.post-67187090698637679742011-12-19T12:41:00.000-08:002013-02-28T13:39:53.292-08:00Learning Scala : Reading the exotic and essential List API scaladoc 1
<b><u><i><span style="font-size: xx-small;"><div itemscope itemtype="http://data-vocabulary.org/Person">
Authored by <span itemprop="name">Win Myo Htet</span>
</div></span></i></u></b>
<br />
<b><u><span style="font-size: xx-small;"><br /></span></u></b>
Everything about data manipulation in Scala is <i>List</i>. Of course, I over exaggerate it. Yet, you will be using <i>List</i> more than any other data structure. I have started out learning Scala and run into <i>List</i> over and over. I even theorize that if you know <i>List</i> API, you know Scala and the majority of its API. After all, the majority of the functions in Scala data structure API overlap. I wish, I had learned the <i>List</i> API early and it would have made my life easier. I would have known about the neat function like <i>mkString</i> when I was reading <a href="http://blog.aunndroid.com/2011/11/chewy-code-scala-tictactoe-part-1.html" target="_blank">the Tic Tac Toe code</a>. I wouldn't be doing <i>list.slice(0,list.length-2)</i> or <i>list(list.length-1)</i>. It seems silly now. Yes, I have done those things because I have not read or even skimmed the <i>List</i> API doc while I have been using more advanced functions like <i>foldLeft</i>, <i>flatMap</i> and <i>flatten</i>. If you go look at <a href="https://gist.github.com/wmhtet" target="_blank">my gist repo</a> and look at the first version of gists, you will see that I am telling the truth. <br />
<br />
I don't know about the reader. For me coming from the pretty and greenery <a href="http://developer.android.com/reference/java/util/List.html" target="_blank">Adroid API world</a>, scaladoc seems daunting until I see the <i>C++</i>'s stuff below<br />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code>template <template <class, class> class C,
class T,
class A,
class T_return,
class T_arg
>
C<T_return, typename A::rebind<T_return>::other>
map(C<T, A> &c,T_return(*func)(T_arg) )
{
C<T_return, typename A::rebind<T_return>::other> res;
for ( C<T,A>::iterator it=c.begin() ; it != c.end(); it++ ){
res.push_back(func(*it));
}
return res;
}
</code></pre>
<br />
I feel blessed. Enough with the intro, let's look at the <a href="http://www.scala-lang.org/api/current/index.html#scala.collection.immutable.List" target="_blank"><i>List API</i></a>. Please open the link in the different browser window while you are reading the blog since I will be referring to it as I talk about the <i>List</i>.<br />
<br />
Well, Scaladoc API also is pretty, it's just packed with a lot of information. At the top most section, we have the package name: <i>scala.collection.immutable</i> and then the class name: <i>List</i>. The section is followed by the class signature section stating that <i>List</i> extends <i>LinearSeq</i> and have <i>trait</i>'s of <i>Product</i>, <i>GenericTraversableTemplate</i> and <i>LinearSeqOptimized</i>. <i>[+A]</i> means that <i>List</i> is covariant. Don't worry about <i>[+A],</i> it just likes java Generic.<br />
<br />
The description section explains a bit about the class with the missing info from class signature like <i>Attributes : sealed abstract, </i>which means all the sub classes (for <i>List:</i> <i>Nil</i> and <i>::</i>) of<i> </i> the sealed class (<i>List</i>) must be in the same source file so that, when the pattern matching is used, the compiler can warn about whether the match is exhaustive or not. We also have the link for easy access to view the source file. You will see <i>Nil</i> on line 368 and <i>::</i> on line 390 in the same <i>List </i>source file. There are more info about the version numbers. The <i>Linear Supertypes </i>provide information of the multiple inheritance (without <a href="http://en.wikipedia.org/wiki/Diamond_problem" target="_blank">diamond problem</a>). There is also information on Subclasses.<br />
<br />
At first, this section seems like more redundant information about the class with in-page-search box, which is neat. So, let's call this section, <i>"Search section</i>", which we will be using a lot later. This section is really powerful and will make you appreciate this official Scala API. By default, the following is selected <i>Ordering : Alphabetic, Inherited : Show all, Visibility : Public.</i> If you select <i>By inheritance</i> in <i>Ordering</i>, you will see all the List's value members ordered in a way the members are inherited. That way, you can track which member is inherited from which class if you are interested in it. "<i>Hide all</i>" does not really hide all. It leaves <i>List</i>'s own concrete value members, which makes sense. From there one can toggle the classes interested in to see the particular class' value member only. <i>Visibility : All</i> will show the <i>protected</i> members also.<br />
<br />
Now, we are left with <i>Instance Constructors, Type Members, Abstract Value Members, Concrete Value Members </i>and<i> Deprecated Value Members</i> sections. <i>Instance Constructors</i> is for <i>Constructor</i> method. <i>Type Member</i> can be assumed as <i>inner </i><i>Class</i> Member, if you are not familiar with the Scala type system yet. <i>Abstract Value Members</i> is the abstract methods without implementation and values without initialization. <i>Concrete Value Members</i> are the ones we will be using. Needless to say, we won't be using any of the <i>Deprecated Value Members</i>.<br />
<br />
Let me skip the Constructor stuff and get to <i>Type Members</i>. Here we have the inner class like member <i>WithFilter</i> class. What do we do with this? How are we going to use it? We don't have to do anything with this. Then, why is it there? It is there because <i>List</i> have inherited it from <i>TraversableLike</i>. If you go to <i>Search Section</i> and click on <i>Hide all</i>, <i>TraversableLike</i> and <i>List</i> (to hide List's stuff) under <i>Inherited</i>, you will still see <i>Type Members</i> <i>class WithFilter</i> along with some <i>Concrete Value Members. </i>If you scroll down, you will see function <i>withFilter</i> in the <i>Concrete Value Members</i>. If you go look at the <a href="http://www.scala-lang.org/api/current/index.html#scala.collection.TraversableLike" target="_blank"> </a><a href="http://www.scala-lang.org/api/current/index.html#scala.collection.TraversableLike" target="_blank">TraversableLike<i> </i>source code</a>, you will see this class <i>WithFilter</i>(line 639) and function <i>withFilter</i>(line 634) there. You are like, "Ok, fine, just show me how to use it." Now we know that function <i>withFilter</i> is the one we are interested in for usage.<br />
<br />
If we expand and look at the definition of <i>withFilter</i>, we know that it takes a <i>predicate</i> (a function returning a Boolean) as a parameter and return <i>FilterMonadic</i> stuff. Wow, Scary! Let's read a bit more. There is a note mentioning about the difference between <i>filter</i> and <i>withFilter</i>. If it talks about the difference, it must be similar! It is said that, compare to <i>filter</i>, <i>withFilter</i> does not create a new collection when doing the filtering, thus <i>withFilter </i>is the optimized version of the <i>filter</i>! We want to use the optimized version, <i>withFilter</i> then. There is more info on the <i>FilterMonadic </i>in the <i>return</i> type description. It is said that <i>FilterMonadic </i>is some object which support <i>map, flatMap, foreach </i>and<i> withFilter</i>. Well, let's give it a try then.<br />
<br />
<br />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code>scala> val list=List(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15)
list: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15)
scala> list.withFilter(num=>num%2==0)
res0: scala.collection.generic.FilterMonadic[Int,List[Int]] = scala.collection.TraversableLike$WithFilter@431067af
scala> list.withFilter(num=>num%2==0)foreach(println)
2
4
6
8
10
12
14
scala> list.filter(num=>num%2==0)foreach(println)
2
4
6
8
10
12
14
scala> list.filter(num=>num%2==0)
res3: List[Int] = List(2, 4, 6, 8, 10, 12, 14)
scala> list.filterNot(num=>num%2==0)
res4: List[Int] = List(1, 3, 5, 7, 9, 11, 13, 15)
scala>
</code></pre>
<br />
Ah... the <i>FilterMonadic </i>thingy is not scary after all. We just need to use it with<i> map, flatMap, foreach </i>and<i> withFilter</i> only. Now we have knocked <i>withFilter</i> and <i>filter</i> off from the List API's functions list for us to learn. Oh, I have squeezed in the <i>filterNot</i> too if you pay attention. <br />
<br />
How do we get to the near bottom of the List API Scaladoc? We come here through <i>Type Memeber.</i> Well, then let's get back to where we are next. <a href="http://blog.aunndroid.com/2011/12/learning-scala-reading-exotic-and_21.html" target="_blank">Shall we?</a><br />
<br />
<br />
<b><u><i><span style="font-size: xx-small;"><div itemscope itemtype="http://data-vocabulary.org/Person">
Authored by <span itemprop="name">Win Myo Htet</span>
</div></span></i></u></b>
<b><u><i><span style="font-size: xx-small;"></span></i></u></b>
Win Myo Htethttp://www.blogger.com/profile/12932751895421525726noreply@blogger.com0tag:blogger.com,1999:blog-8495049179494016066.post-12233924456612188132011-12-07T18:39:00.000-08:002013-02-28T13:39:22.896-08:00Learning Scala : upper bound "<:" and lower bound ">:" for laypeople
<b><u><i><span style="font-size: xx-small;"><div itemscope itemtype="http://data-vocabulary.org/Person">
Authored by <span itemprop="name">Win Myo Htet</span>
</div></span></i></u></b>
<br />
<b><u><span style="font-size: xx-small;"><br /></span></u></b>
Scala has a very rich type system. One aspect of the type system is <i>variance</i>, which is annotated by "+" or "-" or " " (e.g. <i>List[+A]</i>). From that, we also have lower bound and upper bound. We are not going to get into the detail of it. We will only try to understand it from the object oriented analogy. Generally, lower bound, ">:", can be seen as <i>[Parent >: Child]</i> format and upper bound, "<:", as <i>[Child<:Parent]</i>. They are there for the proper usage of the Scala generic. A code snippet is worth a thousand words. So, here is the code:<br />
<br />
<pre class="brush: scala">abstract class Animal (animalType:String)
class HasFourLegs(animalType:String) extends Animal(animalType){
def move=println(this+" walking on four legs")
}
class HasTwoLegs(animalType:String) extends Animal(animalType){
def move=println(this+" walking on Two legs")
}
case class Dog(animalType:String) extends HasFourLegs(animalType)
case class Ostrich(animalType:String) extends HasTwoLegs(animalType)
def moveOn4legs[T<:HasFourLegs](animal:T)= animal.move
val dog = Dog("dog")
val ostrich=Ostrich("ostrich")
moveOn4legs(dog)
/*
moveOn4legs(ostrich)
error: inferred type arguments [this.Ostrich] do not conform to method moveOn4legs's type parameter bounds [T <: this.HasFourLegs]
moveOn4legs(ostrich)
^
*/
println
class AnimalMovement [+T]{
def movement[U>:T](animal:U)=println(animal+" walking on Two legs!!!")
}
val moveLikeTwoLegs=new AnimalMovement[HasTwoLegs]()
moveLikeTwoLegs.movement(ostrich)
moveLikeTwoLegs.movement(dog)
</pre>
<br />
We have two kinds of animals: 4 legs and 2 legs. From there, we have a Dog and an Ostrich. We then have a method, <i>moveOn4legs</i>, with upper bound parameterized as <i>moveOn4legs[T<:HasFourLegs]</i>, thus restricting the paramter type to be the Child of <i>HasFourLegs</i> class. We can only use this method for <i>Dog</i> which extends <i>HasFourLegs</i>. We get compile time error when we use Ostrich which does not extends <i>HasFourLegs.</i><br />
<br />
Now we get to the <i>AnimalMovement</i> class with <i>[+T]</i>, which is <i>covariance</i>. (<i>[-T] </i>is<i> contravariance </i>and<i> [T] </i>is<i> invariant</i>). Inside it, we have a parameterized method with lower bound, <i>movement[U>:T](animal:U)</i>. We create an object, <i>moveLikeTwoLegs</i>, out of it with the type <i>HasTwoLegs</i>. The <i>movement</i> method is then invoked with both dog and ostrich. Here is the output of this whole code snippet.<br />
<br />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code>aunndroid@ubuntu:/host/linux/learning_scala/notes$ scala upper_lower_Bound.scala
Dog(dog) walking on four legs
Ostrich(ostrich) walking on Two legs!!!
Dog(dog) walking on Two legs!!!
</code></pre>
<br />
From, the print out of the last two lines, we see that lower bound let us use dog, an object of DOG, which is not a Child of <i>HasTwoLegs </i>but of <i>HasFourLegs, </i>which shares the same Parent <i>Animal</i><i>. </i><br />
<br />
Of course, proper usage of the terms should be <i>supertype</i> for <i>Parent </i>and <i>subtype </i>for <i>Child</i> but we just want to grasp the concept of upper bound "<:" and lower bound ">:" only.<br />
<br />
<br />
<b><u><i><span style="font-size: xx-small;"><div itemscope itemtype="http://data-vocabulary.org/Person">
Authored by <span itemprop="name">Win Myo Htet</span>
</div></span></i></u></b>
Win Myo Htethttp://www.blogger.com/profile/12932751895421525726noreply@blogger.com0tag:blogger.com,1999:blog-8495049179494016066.post-57201855552492916392011-11-30T15:34:00.000-08:002013-02-28T13:38:43.087-08:00Learning Scala : "case class", twitter interview question?<b><u><i><span style="font-size: xx-small;"><div itemscope itemtype="http://data-vocabulary.org/Person">
Authored by <span itemprop="name">Win Myo Htet</span>
</div></span></i></u></b>
<br />
<b><u><span style="font-size: xx-small;"><br /></span></u></b>
I have been learning Scala actively and reading blogs, stackoverflow, and books; browsing repo, getting my hands dirty coding snippet and writing blog. I come to this subject "case class". Well, I have to admit that reading the books is boring unlike blog, yet, the books are more reliable sources of information (oh yeah? You don't know that ?) Then, there is stackoverflow, which is more reliable, does not detour and gives instant enlightened answers/insights proof-read by professionals. Still, the book does a better job of explaining (better experience on ebook with the help of Glossary and Index) Yes, I will talk about the "case class". I digress in introduction!<br />
<br />
As I crawl the internet to learn Scala, I have downloaded some twitter's open source popular repos on <a href="https://github.com/twitter" target="_blank">github</a>. I have browsed, skimmed and searched the repos to see how the early scala adopter is using it and defining the Scala usage pattern. Here are the downloaded repos(watchers) : flockdb (1,133), finagle(592), gizzard(966), killdeer(18) and ostrich(179). With only these opened in the eclipse, I use eclispe search tool for some of the thing I am interested in. Search keyword and number found paired.<br />
<br />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code>tailrec 17
foldLeft 19
foldRight 0
for 2945 /*This includes "for" from code comment*/
while 152 /*This also includes "while" from code comment*/
</code></pre>
<br />
Yup, at that time, I want to know how pervasive is the <a href="http://blog.aunndroid.com/2011/11/learning-scala-recursion-and-tco-1.html" target="_blank"><i>TCO'ed recursion</i></a> and <i>fold</i> usages. I guess, <i>for-comprehension</i> rules the day. And I also skim through the codes and notice quite a lot of <i>case</i> block matchings. So here are some stats:<br />
<br />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code>case 1658 /*This includes "just in case ..." kind of comment*/
case class 187 /*don't know if this words pair can be in comment*/
</code></pre>
<br />
Now I hope to have your attention on the seriousness of the subject matter. It will be on the twitter interview questions! Ok, how is "<i>case class</i>" different from "<i>class</i>"? What is "<i>case class</i>"? "<i>case class</i>" is just a <i>class</i>. Ok... It adds extra niceties-methods : <i>copy, equal</i>, <i>hashcode</i> and (prettier) <i>toString</i>. The important part is that when "<i>case class</i>" is used, the compiler creates <i>companion object </i>which has both <i>apply</i> and <i>unapply</i> methods. "<i>apply(variables)</i>" method in Scala can be replaced with just "<i>(variables)</i>", thus "<i>case class</i>" enables constructor without keyword "<i>new</i>".<br />
<br />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code>scala> case class MyCaseClass(name:String,isCase:Boolean)
defined class MyCaseClass
scala> val myCaseClass=MyCaseClass("myCaseClass",true)
myCaseClass: MyCaseClass = MyCaseClass(myCaseClass,true)
scala> class MyClass(name:String,isCase:Boolean)
defined class MyClass
scala> val myClass=MyClass("myClass",false)
<console>:7: error: not found: value MyClass
val myClass=MyClass("myClass",false)
^
scala> val myClass=new MyClass("myClass",false)
myClass: MyClass = MyClass@be7f971
</code></pre>
<br />
So the interviewer asks "Why is that "<i>case class</i>" constructor does not require "<i>new</i>" keyword while the regular one does?" Then, you will answer "Cause the compiler generate "<i>companion object"</i> with "<i>apply</i>" method which can be omitted" Then, the interviewer will ask "We don't care much about "<i>new</i>" keyword but we just want to use regular class and want the benefit of <i>case</i> pattern matching. How would you do that?" Don't worry. Here is the answer for you. "<i>case class</i>" pattern matching is made possible by <i>companion object</i>'s <i>unapply</i> extractor method. So we just need to do what "<i>case class</i>" does!<br />
<br />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code>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> case class MyCaseClass(name:String,isCase:Boolean)
defined class MyCaseClass
scala> :paste
// Entering paste mode (ctrl-D to finish)
class MyClass(val name:String,val isCase:Boolean)
object MyClass {
def unapply(myClass:MyClass):Option[(String,Boolean)]={
if(myClass eq null) None
Some((myClass.name,myClass.isCase))
}
}
// Exiting paste mode, now interpreting.
defined class MyClass
defined module MyClass
scala> val myCaseClass=MyCaseClass("myCaseClass",true)
myCaseClass: MyCaseClass = MyCaseClass(myCaseClass,true)
scala> val myClass=new MyClass("myClass",false)
myClass: MyClass = MyClass@7bc2f501
scala> val classList=List(myClass,myCaseClass)
classList: List[ScalaObject] = List(MyClass@7bc2f501, MyCaseClass(myCaseClass,true))
scala> for( x <- classList) x match{
| case MyCaseClass(name,isCase)=>println(x+" "+name+" "+isCase)
| case MyClass(name,isCase)=>println(x+" "+name+" "+isCase)
| }
$line2.$read$$iw$$iw$MyClass@7bc2f501 myClass false
MyCaseClass(myCaseClass,true) myCaseClass true
scala>
</code></pre>
<br />
In case, if you miss it, I have started the new <i>repl</i> session and redefine the classes. You will notice the "<i>:paste</i>" before <i>MyClass</i> definition tho. It is because we want the <i>repl</i> session to know that the following <i>object</i> with <i>unapply</i> method is the <i>companion object</i> to the <i>class</i> above. If you forget "<i>:paste</i>", don't worry, the <i>repl</i> will warn you. "<i>unapply</i>" method takes <i>MyClass</i> object and return the fields like the default constructor wrapped in the <i>Option</i>. Then we see the <i>unapply</i> extractor method of <i>MyClass</i> at work for pattern matching in the <i>for</i> loop near the bottom like <i>MyCaseClass</i>. Do you notice how pretty "<i>case class</i>" makes <i>MyCaseClass</i>'s <i>toString</i> ? Your interviewer will then said "Ok, I am convinced that "<i>case class" </i>is better. What else does it do? How about if I want a new constructor?" Well, "<i>case class</i>" makes default constructor fields to be <i>immutable</i> (Scala always encourages <i>immutable</i> type.), so you don't have to state "<i>val</i>" explicitly. However, you will have to do that for "var" tho. If you want new constructor, you can create them yourself but to use it, you have to use "<i>new</i>" keyword because there won't be any compiler generated overloaded <i>"apply"</i> method for that new constructor.<br />
<br />
Then, the interviewer is happy and you get the job at twitter. Don't forget me when twitter goes IPO and you become rich,OK?<br />
<br />
<b><u>Update</u></b><br />
So, one interviewee came back to me and said that the interviewer said there are more to the <i>case class</i>. Well, if it is said so, let's take a look:<br />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code>
aunndroid@ubuntu:/host/linux/learning_scala/notes$ cat MyCaseClass.scala
case class MyCaseClass(name:String,isCase:Boolean){
override def productPrefix="MyPrettyCaseClass"
}
</code></pre>
<br />
We will use <i>scalac -print</i> option to peep into it. Please do it at home, it is safe. Actually I have omitted some interesting lines of codes for brevity, that's why.<br />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code>
aunndroid@ubuntu:/host/linux/learning_scala/notes$ scalac -print MyCaseClass.scala
[[syntax trees at end of cleanup]]// Scala source: MyCaseClass.scala
package <empty> {
case class MyCaseClass extends java.lang.Object with ScalaObject with Product with Serializable {
.
.
.
};
final <synthetic> object MyCaseClass extends scala.runtime.AbstractFunction2 with ScalaObject with Serializable {
.
.
.
}
}
</code></pre>
<br />
Now, we know that <i>case class</i> also has mixin of <i>Serializable</i> and <i>Product</i> trait. We know <i><a href="http://en.wikipedia.org/wiki/Serialization" target="_blank">Serializable</a>. </i>What is <i>Product</i>? <i>Product</i> enables the case class' fields to be accessed without reflection. Here is the <a href="http://www.scala-lang.org/api/current/index.html#scala.Product" target="_blank"><i>Product</i> scaladoc API</a> and the following is the code snippet.<br />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code>
aunndroid@ubuntu:/host/linux/learning_scala/notes$ scala
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> :load MyCaseClass.scala
Loading MyCaseClass.scala...
defined class MyCaseClass
scala> val myCaseClass=MyCaseClass("aunnDroidCaseClass",true)
myCaseClass: MyCaseClass = MyPrettyCaseClass(aunnDroidCaseClass,true)
scala> myCaseClass.productArity
res3: Int = 2
scala> myCaseClass.productElement(0)
res4: Any = aunnDroidCaseClass
scala> myCaseClass.productElement(1)
res5: Any = true
scala> for(x <- myCaseClass.productIterator)println(x)
aunnDroidCaseClass
true
scala> myCaseClass.productPrefix
res7: java.lang.String = MyPrettyCaseClass
</code></pre>
<br />
We have skipped the <i>canEqual</i> function. <i>productArity</i> provides the number of fileds in the class while <i>productElement (n: Int)</i> let us access those field with index. <i>productIterator</i> gives us the <i>Iterator[Any] </i>object which we use with for comprehension to print out the fields. We have <i>overriden</i> <i>productPrefix</i>, which is part of the reason why the <i>case class</i> has a pretty <i>toString</i> method. <br />
<br />
Hope the interviewer is happy this time.<br />
<br />
<b><u><i><span style="font-size: xx-small;"><div itemscope itemtype="http://data-vocabulary.org/Person">
Authored by <span itemprop="name">Win Myo Htet</span>
</div></span></i></u></b>
<b><u><i><span style="font-size: xx-small;"></span></i></u></b>
Win Myo Htethttp://www.blogger.com/profile/12932751895421525726noreply@blogger.com0tag:blogger.com,1999:blog-8495049179494016066.post-67897091008589371772011-11-22T23:07:00.000-08:002013-02-28T13:38:13.058-08:00Learning Scala : Recursion and TCO 2<div itemscope="" itemtype="http://data-vocabulary.org/Person">
<b><u><i><span style="font-size: xx-small;">Authored by <span itemprop="name">Win Myo Htet</span>
</span></i></u></b></div>
<br />
<br />
<br />
In the previous <a href="http://blog.aunndroid.com/2011/11/learning-scala-recursion-and-tco-1.html" target="_blank">post</a>, we talk about the TCO. Now, we will do some TCO'ed recursion exercise. I have picked an example from "<a href="http://www.amazon.com/Programming-Interviews-Exposed-Secrets-Programmer/dp/047012167X" target="_blank">Programming Interviews Exposed</a>" on P.97. Here is the problem definition : "<i>Implement a function that prints all possible combinations of the characters in a string. These combinations range in length from one to the length of the string. Two combinations that differ only in ordering of their characters are the same combination. In other words, "ab" and "ca" are different combinations from their input string "abc". But "ba" is the same as "ab"</i>"<br />
<br />
We want to write a tail call recursive code with accumulator, which will give us the final result, at the end of iteration. We have to remember that we don't want any computation on the way back in these recursive calls. We will accumulate the result along the way so that we don't have to do backtrack computing. Before we go on analyzing the code, let me disclose something first. In the past, when I started coding, I tried to implement this problem by myself without reading at the authors' analysis. I failed. :) I was quite frustrated with my attempts and didn't try it again until I have started learning recursion in Scala. I try again this time. Yay! I made it. ;) With these experience, I have understood the problem and answer well. I am able to do educated grouping to form some patterns.<br />
<br />
Yet, I still need paper and pencil! Nothing can beat paper and pencil in this age of computing when it comes to do pattern analyzing scratches for the problem. Holding pencil in the right hand like a sword, while paper in the left hand like a shield, I march on! When I am implementing the simple recursion for this problem, I look at the two logically grouped tables in the book (I won't be drawing these tables here. <a href="http://www.amazon.com/Programming-Interviews-Exposed-Secrets-Programmer/dp/047012167X" target="_blank">Buy</a> the book!) It helps me with my thinking and visualizing of the data grouping and the flow of the data in the code too. Now, I am trying to go through the data flow where I don't have to backtrack for computing, the following data flow emerge.<br />
<br />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code>
input: w x y z
=======
result: w wx wxy wxyz wxz wy wyz wz x xy xyz xz y yz z
mydata flow
-----------
w
x
wx
y
wy xy
wxy
z
wz xz
wxz
yz
wyz xyz
wxyz
</code></pre>
<br />
<b><u><i><span style="font-size: xx-small;">Authored by Win Myo Htet</span></i></u></b>
<br />
<b><u><span style="font-size: xx-small;"><br /></span></u></b>
<b><u><span style="font-size: xx-small;"><br /></span></u></b>
First, we will have 'w', which we will carry it in our accumulator to the next iteration. Then, we have 'x'. We will keep the 'w'. We want to add 'x' and also our first combination of character 'wx' too. I would like to go over this again. We start with 'w'. Carry it over. Get a new character 'x', keep the 'w', add the new 'x' and add 'w' and 'x' combination. Carry all these over in the accumulator to the next iteration. We still want to keep whatever we have before and add a new 'y' and the new characters combinations of 'y' and the previous list. Now, you know what happens to Z. If you don't, well, read this whole paragraph recursively until you get it. ;)<br />
<br />
So basically, we have the accumulator and add a new character to the accumulator and also add a new list which has the combination of the new character with the string in the accumulator. Cool!<br />
<br />
<pre class="brush : scala">import scala.annotation.tailrec
final def tailReccursionEx(str : String) : List[String] = {
@tailrec
def doTailRecursionEx(str : String, pos : Int, accu : List[String]) : List[String] = {
if (pos == str.length) return accu
else {
val newAccu = accu ++ accu.foldLeft(List[String](str(`pos`).toString)) {
(l, ch) => l :+ ch + str(`pos`)
}
doTailRecursionEx(str, pos + 1, newAccu)
}
}
doTailRecursionEx(str, 0, List[String]())
}
</pre>
<br />
To make life simpler, I have started <i>foldLeft</i> process with the List with the new character. You can get the complete source code <a href="https://gist.github.com/1387911" target="_blank">here</a> .<br />
<br />
When you look at the complete source code from the provided git repo link. You will see the comparison of imperative, recursion and TCO'ed recursion. They all look comparable. <a href="https://gist.github.com/1387374" target="_blank">Here</a> is another FP recursion implementation from the book (the one after the above example). When I implement the regular recursion, I am able to write it out. However, I have to make considerable effort to get it TCO'ed. The TCO'ed code is more verbose than regular recursion and at the same time also suffer from the performance impact. <br />
<br />
Why do we want TCO again? To prevent side effect. To prevent stack over flow. To prevent our precious application from crashing. Is TCO worth the time and energy? Do you have better tip and trick ? Please let me know. I get to this haskell <a href="http://lambda-the-ultimate.org/node/2673" target="_blank">thread</a> when I start looking into recursion via <a href="http://en.wikipedia.org/wiki/Ackermann_function" target="_blank">Ackermann</a>. I was thinking of implementing <a href="https://gist.github.com/1387917" target="_blank">it</a> TCO'ed. Having read the thread and seeing the TCO destroy the beauty of recursion and the extent needed to go to achieve the TCO, I don't want to try anymore. Yup, these are the ugly sides of FP and recursion. It is the different side of the same coin. We need to have discussion going how to tackle these issue to get FP traction for wider use. Here is one of the methods called <a href="http://blog.richdougherty.com/2009/04/tail-calls-tailrec-and-trampolines.html" target="_blank">trampoline</a> to address some TCO issue in Scala. It is still not easy to use. It is advanced stuff. Well, it's an option.<br />
<br />
<a href="http://stackoverflow.com/questions/8238820/how-to-approach-implementing-tcoed-recursion" target="_blank">StackOverflow discussion on this</a>.<br />
<br />
<br />
<div itemscope="" itemtype="http://data-vocabulary.org/Person">
<b><u><i><span style="font-size: xx-small;">Authored by <span itemprop="name">Win Myo Htet</span>
</span></i></u></b></div>
Win Myo Htethttp://www.blogger.com/profile/12932751895421525726noreply@blogger.com0tag:blogger.com,1999:blog-8495049179494016066.post-23882591505801801732011-11-22T18:40:00.000-08:002013-02-28T13:37:44.992-08:00Learning Scala : Recursion and TCO 1<b><u><i><span style="font-size: xx-small;"></span></i></u></b><br />
<div itemscope="" itemtype="http://data-vocabulary.org/Person">
<b><u><i><span style="font-size: xx-small;">Authored by <span itemprop="name">Win Myo Htet</span>
</span></i></u></b><br />
<b><u><span style="font-size: xx-small;"><br /></span></u></b>
<b><u><span style="font-size: xx-small;"><br /></span></u></b></div>
<br />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code>fib=1:1[a+b|(a,b)<-zip fib(tail fib)]
</code></pre>
My buddy texted me the above Haskell Fibonacci code, which uses recursion, of course. Very neat, huh? We have also seen recursion making <a href="http://blog.aunndroid.com/2011/11/learning-scala-writing-quicksort.html" target="_blank">QuickSort</a> self documenting and gracefully simple. I have also used recursion in my <a href="http://blog.aunndroid.com/2011/11/learning-scala-boyermoore-search-1.html" target="_blank">Boyer-Moore</a> search without making a conscious effort. Yes, recursion is at home in functional programming. <br />
<br />
Recursion can make thing simple. Yet, simple is not easy! It takes recursively using recursion to master recursion. Ok, that's not a very good joke. But you get the point that you need to keep using recursion whenever possible to learn to think in recursion if you want to be the master in the land of functional programming. In Scala, you can get away with, without using recursion, then, you are not really in functional programming land. Assume that you have decided to start using recursion buying into my much lauded hype, well, let me raise the bar a bit then. With great power comes ... I mean, "With Recursion comes this nasty bug stack overflow."<br />
<br />
Great... Well, all hope is not lost, sort of... The stack overflow happens because the function keeps calling itself thus putting itself on the stack memory again and again until it runs out of stack memory. The remedy to this is TCO (Tail Call Optimization). In TCO, we are using a particular pattern of recursion so that the compiler can optimize the code to avoid the stack overflow. Let's try lookat some code.<br />
<br />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code>scala> List(1,2,3,4,5,6).foldLeft(10)(_ + _)
res0: Int = 31
</code></pre>
<br />
Are we still talking about recursion? Yes, we are. I have mentioned in one of the <a href="http://blog.aunndroid.com/2011/11/learning-scala-boyermoore-search-2.html" target="_blank">blog</a> before that <i>foldLeft</i> is preferred over foldRight. The reason being is that <i>foldLeft</i> is TCO'ed while <i>foldRight</i> is not. Here is a bit detail analysis of their process.<br />
<br />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code>Here is the foldLeft sequence:
((((((10 + 1) + 2) + 3) + 4) + 5) + 6)
((((((11) + 2) + 3) + 4) + 5) + 6)
(((((13) + 3) + 4) + 5) + 6)
((((16) + 4) + 5) + 6)
(((20) + 5) + 6)
((25) + 6)
(31)
Here is the foldRight sequence:
(1 + (2 + (3 + (4 + (5 + (6 + 10))))))
(1 + (2 + (3 + (4 + (5 + (16))))))
(1 + (2 + (3 + (4 + (21)))))
(1 + (2 + (3 + (25))))
(1 + (2 + (28)))
(1 + (30))
(31)
</code></pre>
<br />
In <i>foldLeft</i>, you can see that the result can be computed before the next iteration, while <i>foldRight</i> have to traverse all the way to the end, then compute and backtrack for more computing. Alright, how do we do that for our own Fibonacci code? Following the above <i>foldLeft </i>example, here is our Fibonacci code<br />
<br />
<pre class="brush : scala">object Fibonacci{
def main(args:Array[String]):Unit={
println(fibonacci(6))
}
import scala.annotation.tailrec
private def fibonacci(n:Int):Int={
@tailrec
def fibonacciTCO(n:Int,accu:Int):Int={
if(n==1) return n+accu
fibonacciTCO(n-1,n+accu)
}
fibonacciTCO(n,10)
}
}
</pre>
<br />
<b><u><i><span style="font-size: xx-small;">Authored by Win Myo Htet</span></i></u></b>
<br />
<b><u><span style="font-size: xx-small;"><br /></span></u></b>
We have to include proper <i>import</i> above <i>fibonacci</i> and <i>@tailrec annotation</i> above <i>fibonacciTCO. </i>The <i>fibonacci </i>function has to be declared <i>private</i> or <i>final </i>so that the method cannot be overridden to undo the TCO. You also need to have accumulator (e.g. In our case <i>accu</i>) so that we can carry on our result and return the final result at the last iteration without needing to backtrack all the way back. If you look carefully at the code, you will notice that, our (near ?) result(<i>accu</i>) is always in the same function scope and the stack reference to the previous call is not needed any more. Now, to make sure that our method is TCO'ed, we will look into the byte code of our compilation using <i>javap</i> with <i>-c</i> and <i>-private</i> option on the class file of <i>Fibonacci$.class</i> itself.<br />
<br />
<pre class="brush : bash">aunndroid@ubuntu:/host/Users/aunndroid/workspace/source_code$ javap -c -private Fibonacci\$
Compiled from "fibonacci.scala"
public final class Fibonacci$ extends java.lang.Object implements scala.ScalaObject{
public static final Fibonacci$ MODULE$;
public static {};
Code:
0: new #9; //class Fibonacci$
3: invokespecial #12; //Method "<init>":()V
6: return
public void main(java.lang.String[]);
Code:
0: getstatic #19; //Field scala/Predef$.MODULE$:Lscala/Predef$;
3: aload_0
4: bipush 6
6: invokespecial #24; //Method fibonacci:(I)I
9: invokestatic #30; //Method scala/runtime/BoxesRunTime.boxToInteger:(I)Ljava/lang/Integer;
12: invokevirtual #34; //Method scala/Predef$.println:(Ljava/lang/Object;)V
15: return
private int fibonacci(int);
Code:
0: aload_0
1: iload_1
2: bipush 10
4: invokespecial #42; //Method fibonacciTCO$1:(II)I
7: ireturn
private final int fibonacciTCO$1(int, int);
Code:
0: iload_1
1: iconst_1
2: if_icmpne 9
5: iload_1
6: iload_2
7: iadd
8: ireturn
9: iload_1
10: iconst_1
11: isub
12: iload_1
13: iload_2
14: iadd
15: istore_2
16: istore_1
17: goto 0
private Fibonacci$();
Code:
0: aload_0
1: invokespecial #48; //Method java/lang/Object."<init>":()V
4: aload_0
5: putstatic #50; //Field MODULE$:LFibonacci$;
8: return
}
aunndroid@ubuntu:/host/Users/aunndroid/workspace/source_code$
</init></init></pre>
<br />
Don't worry too much if you don't know anything here. Well, if you know everything and if you are the master of the Scala Universe, you might even not bother to read this, right ? ;) So, we find our TCO'ed <init><i>fibonacciTCO$1</i></init><init>, at line 30. At line 47, instead of re-referencing itself, we find this </init><init><i>17: goto 0.</i></init><init> When you see that <i>goto</i> expression, you can be rest assured that your tail call recursion has been TCO'ed. The tail call recursion get optimized by scala compiler using <i>goto</i>. Compare to other functional languages, Scala has some restraints. Since Scala run on JVM and JVM does not support TCO(yet), Scala requires that tail call recursion must be self recursive tail call (e.g. </init><init><i>fibonacciTCO </i></init><init>must call</init><init><i> </i></init><init><i>fibonacciTCO</i></init><init>).</init><br />
<br />
Yup, that's quite a bit of info. I don't conceive these knowledge auto-magically. I am not the creator of Scala. I have read the blogs and books. So, I also recommend you to keep on reading about recursion and encourage you to blog about it too. Reading the same info from different narration will help you grasp the concept better. Here are the two I have read: <a href="http://grahamhackingscala.blogspot.com/2010/04/ensuring-tail-call-optimization-in.html" target="_blank">Graham's blog</a> and <a href="http://stronglytypedblog.blogspot.com/2009/08/scala-tail-recursion.html" target="_blank">Nick's blog</a>. They are also explaining the same info in their own way. As usual, we will be getting into some code in the next <a href="http://blog.aunndroid.com/2011/11/learning-scala-recursion-and-tco-2.html" target="_blank">blog</a> in this series.<br />
<br />
<br />
<b><u><i><span style="font-size: xx-small;"></span></i></u></b><br />
<div itemscope="" itemtype="http://data-vocabulary.org/Person">
<b><u><i><span style="font-size: xx-small;">Authored by <span itemprop="name">Win Myo Htet</span>
</span></i></u></b></div>
<b><u><i><span style="font-size: xx-small;"></span></i></u></b>
Win Myo Htethttp://www.blogger.com/profile/12932751895421525726noreply@blogger.com1tag:blogger.com,1999:blog-8495049179494016066.post-77992145325855330082011-11-18T13:07:00.000-08:002013-02-28T13:36:59.359-08:00Learning Scala : Boyer–Moore search 3
<b><u><i><span style="font-size: xx-small;"><div itemscope itemtype="http://data-vocabulary.org/Person">
Authored by <span itemprop="name">Win Myo Htet</span>
</div></span></i></u></b>
<br />
<b><u><span style="font-size: xx-small;"><br /></span></u></b>
We have both the first table and second. Now we just need to create a <i>startSearch </i>method, which will take the two tables and two Strings : searchBody and searchString. We will return a <i>List[Int]</i>, which will have positions of the match strings, thus the size will be the number of the matches.<br />
<br />
<pre class="brush : scala">def startSearch(searchBody : String, searchString : String,
pos : Int, table1 : Map[Int, Int],
table2 : Map[Char, Int]) : List[Int] = {
def search(pos : Int, inc : Int = 0) : List[Int] = {
if (pos >= searchBody.length - 1) return List[Int]()
val jump = matchChar(pos + searchString.length - 1, inc)
if (jump > 0) return search(pos + jump, 0)
if (jump == 0) return search(pos, inc + 1)
if (jump == -1)
return pos :: search(pos + searchString.length, 0)
List[Int]()
}
def matchChar(pos : Int, inc : Int) : Int = {
if (!searchBody.isDefinedAt(pos - inc)) return -2
if (!table2.isDefinedAt(searchBody(pos)))
return searchString.length
if (searchBody(pos - inc)
== searchString(searchString.length - 1 - inc)) {
if (searchString.length - 1 - (inc + 1) == -1) return -1
return 0
}
val result1 = table1.get(inc).get
if (!table2.isDefinedAt(searchBody(pos - inc)))
return result1
val result2 = table2.get(searchBody(pos - inc)).get
if (result2 > result1) return result2
result1
}
search(pos)
}
</pre>
<br />
We have two nested functions inside our function. We check the validity of our search continuity by <i>searchBody</i> string length. We invoke <i>matchChar</i> function to get the <i>jump</i> value. -1 means we found a string match. 0 means the character match. All the positive value means, we will jump that much position. The sort of default return is empty list. Inside <i>matchChar</i>, we will do the validity check and return -2, which will fall through our default empty list return in <i>search</i> function. We return the length of the searchString if the last character is not a valid character according to <i>table2</i>. Then, we do the individual character matching. If it is matched, we will check to see it is the last character to match. If it is the last character matched, we found a match String and return -1. If it is not the last character matched, we will return 0. If the characters are not matched, the two tables are referred for the jump value and larger value is return. In case of the character not being in the table2, we cannot jump the whole searchString's length since there still is a possible match inside the range.<br />
<br />
Below is some output. I admit that it is not well tested. You can get the complete source code <a href="https://gist.github.com/1376820" target="_blank">here</a>.<br />
<br />
Look at the two Map values of ANPANMAN<br />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code>aunndroid@ubuntu:/host/Users/aunndroid/workspace/source_code$ scala boyer_moore.scala
Usage: boyer_more string_body search_string
e.g. : boyer_more "HERE IS A SIMPLE EXAMPLE" "ANPANMAN"
Map(A -> 1, M -> 2, N -> 3, P -> 5)
Map(0 -> 1, 5 -> 6, 1 -> 8, 6 -> 6, 2 -> 3, 7 -> 6, 3 -> 6, 4 -> 6)
ANPANMAN
HERE IS A SIMPLE EXAMPLE
-
ANPANMAN
HERE IS A SIMPLE EXAMPLE
-
ANPANMAN
HERE IS A SIMPLE EXAMPLE
-
Match found : 0 Pos :
</code></pre>
<br />
Here is the search replica of step by step <a href="http://www.cs.utexas.edu/~moore/best-ideas/string-searching/fstrpos-example.html" target="_blank">B-M search</a> demo from the <a href="http://www.cs.utexas.edu/~moore/best-ideas/string-searching/index.html" target="_blank">official site</a> <?><br />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code>
aunndroid@ubuntu:/host/Users/aunndroid/workspace/source_code$ scala boyer_moore.scala "HERE IS A SIMPLE EXAMPLE" "EXAMPLE"
Map(E -> 6, X -> 5, A -> 4, M -> 3, L -> 1, P -> 2)
Map(0 -> 1, 5 -> 6, 1 -> 7, 6 -> 6, 2 -> 6, 3 -> 6, 4 -> 6)
EXAMPLE
HERE IS A SIMPLE EXAMPLE
-
EXAMPLE
HERE IS A SIMPLE EXAMPLE
-
EXAMPLE
HERE IS A SIMPLE EXAMPLE
-
EXAMPLE
HERE IS A SIMPLE EXAMPLE
-
EXAMPLE
HERE IS A SIMPLE EXAMPLE
-
EXAMPLE
HERE IS A SIMPLE EXAMPLE
-
EXAMPLE
HERE IS A SIMPLE EXAMPLE
-
EXAMPLE
HERE IS A SIMPLE EXAMPLE
-
EXAMPLE
HERE IS A SIMPLE EXAMPLE
-
EXAMPLE
HERE IS A SIMPLE EXAMPLE
-
EXAMPLE
HERE IS A SIMPLE EXAMPLE
-
EXAMPLE
HERE IS A SIMPLE EXAMPLE
-
EXAMPLE
HERE IS A SIMPLE EXAMPLE
-
EXAMPLE
HERE IS A SIMPLE EXAMPLE
-
EXAMPLE
HERE IS A SIMPLE EXAMPLE
-
Match found : 1 Pos : 17
aunndroid@ubuntu:/host/Users/aunndroid/workspace/source_code$
</code></pre>
<br />
That's it, folk!<br />
<br />
<br />
<b><u><i><span style="font-size: xx-small;"><div itemscope itemtype="http://data-vocabulary.org/Person">
Authored by <span itemprop="name">Win Myo Htet</span>
</div></span></i></u></b>
<b><u><i><span style="font-size: xx-small;"></span></i></u></b>
Win Myo Htethttp://www.blogger.com/profile/12932751895421525726noreply@blogger.com0tag:blogger.com,1999:blog-8495049179494016066.post-47274785675081514502011-11-18T07:42:00.000-08:002013-02-28T13:36:39.975-08:00Learning Scala : Boyer–Moore search 2
<b><u><i><span style="font-size: xx-small;"><div itemscope itemtype="http://data-vocabulary.org/Person">
Authored by <span itemprop="name">Win Myo Htet</span>
</div></span></i></u></b>
<br />
<b><u><span style="font-size: xx-small;"><br /></span></u></b>
<b><u><span style="font-size: xx-small;"><br /></span></u></b>
In the previous <a href="http://blog.aunndroid.com/2011/11/learning-scala-boyermoore-search-1.html" target="_blank">post</a>, I have explained the second table before the first table. The reason is that the second table is easy to understand. We will do the same and code the second table first.<br />
<br />
<pre class="brush : scala">def createTable2(str : String) : Map[Char, Int] = {
val strOps = new StringOps(str).reverse.tail
val result = strOps.foldLeft(Map[Char,Int](),1) {
case ((mMap,pos),ch) if ! mMap.isDefinedAt(ch)
=> (mMap ++ Map(ch -> pos), pos+1)
case ((mMap,pos),ch) => (mMap,pos +1)
}
return result._1
</pre>
We convert our search string, <i>str</i>, to <i>StringOps</i> type, reverse it and drop the first charcter while keeping the rest. If it is of <i>StringOps</i> format, we can do manipulation like <i>List</i>. It is being reversed so that we can operate <i>foldLeft</i> (<i>foldLeft</i> is <a href="http://blog.aunndroid.com/2011/11/learning-scala-recursion-and-tco-1.html" target="_blank">preferred</a> over <i>foldRight</i> whenever it is possible). We drop the first character, which was the last character before because the last character is not considered in the second table. After that, our usual <i>foldLeft</i> manipulates the string to have a <i>tuple</i> of <i>Map[Char,Int]</i> and <i>Int</i>. The last <i>Int</i> is to track the position of the iteration process. We add each character into the <i>Map</i> if it is not there. Anything else, we just increment the <i>pos</i> to track the iteration position. We return the <i>Map</i> from the <i>tuple</i>.<br />
<br />
The second table is done and we will work on the first table. It is pretty much the same pattern: <i>StringOps, reverse, foldLeft, tuple, Map,</i> etc ... The only differences will be calling <i>calculate</i> function and using the <i>filter</i> on the List. <i>filter</i> filters out character based on the condition. Here is <i>filter</i>'s signature "<i>def filter (p: (Char) ⇒ Boolean): String</i>"<br />
<br />
<pre class="brush : scala">def createTable1(str : String) : Map[Int, Int] = {
val strOps = new StringOps(str).reverse
val strList = strOps.foldLeft(List[Char]()) {
case (l, ch) if !l.contains(ch) => ch :: l
case (l, ch) => l
}
val result = strOps.foldLeft(Map[Int, Int](), 0, "") {
case ((mMap, pos, subStr), ch) if pos != 0 => (mMap ++ Map(pos -> calculate(pos, subStr, `str`,
`strList`.filter {
case x if x == ch => false
case _ => true
})), pos + 1, ch + subStr)
case ((mMap, pos, subStr), ch) => (Map(0 -> 1), pos + 1, ch + subStr)
}
result._1
}</pre>
<br />
There also is a (`backtick quote`), which allows us to refer to the variables outside of the scope. So, the general structure of the code is similar to that of the second table. Here we have <i>Map[Int,Int]</i> instead of <i>Map[Char,Int]</i>. I have decided to use <i>Int</i>, the length of sub string for the Map <i>key</i>. <i>strList</i> with <i>filter</i> will give us a new <i>List</i> with valid character. For example, in valid characters <i>List (A,M,N,P)</i>, <strike>M</strike> will generate <i>List (A,N,P).</i> The <i>calculate</i> function will use <i>strList</i> to create a new sub string and get their position in the search string by calling <i>subSetJump</i> function.<br />
<br />
<pre class="brush : scala">def calculate(pos : Int, subStr : String,
str : String, strList : List[Char]) : Int = {
val jList = strList.foldLeft(List[Int]()) {
(j, ch) => subSetJump(ch + `subStr`, `str`) :: j
}
if (jList.max < 0) {
if (subStr.length == 1) return str.length
return calculate(pos - 1, subStr.slice(0, subStr.length),
str, List[Char]())
}
if (str.length - 1 - pos - jList.max == 0)
return calculate(pos - 1, subStr.slice(1, subStr.length),
str, List[Char]())
str.length - 1 - pos - jList.max
}
</pre>
<br />
<pre class="brush : scala">def subSetJump(subStr : String, str : String) : Int = {
val list = (for (i <- 0 until str.length)
yield str.slice(i, i + subStr.length)).toList
list.indexOf(subStr)
}
</pre>
<br />
<i>subSetJump</i> function will return the index or -1 if there is no match. We check the condition on end-of-string, mis-match and zero-jump; and recursively call the <i>calculate</i> function again with the updated <i>pos</i> and <i>subStr</i>. When we call the <i>calculate</i> function again, we are doing the case for backtrack. That means there won't be any variation of sub strings. Thus, I have added the code for that above jList. It can be a bit of redundant and messey but I am a bit more into getting the working code fast ;) .<br />
<br />
calculate function with more code<br />
<pre class="brush : scala">def calculate(pos : Int, subStr : String,
str : String, strList : List[Char]) : Int = {
if (strList.isEmpty) {
val jListMax = subSetJump(subStr, str)
if (jListMax < 0)
return calculate(pos - 1, subStr.slice(1, subStr.length),
str, List[Char]())
if (str.length - 1 - pos - jListMax == 0)
return calculate(pos - 1, subStr.slice(1, subStr.length),
str, List[Char]())
return str.length - 1 - pos - jListMax
}
val jList = strList.foldLeft(List[Int]()) {
(j, ch) => subSetJump(ch + `subStr`, `str`) :: j
}
if (jList.max < 0) {
if (subStr.length == 1) return str.length
return calculate(pos - 1, subStr.slice(0, subStr.length),
str, List[Char]())
}
if (str.length - 1 - pos - jList.max == 0)
return calculate(pos - 1, subStr.slice(1, subStr.length),
str, List[Char]())
str.length - 1 - pos - jList.max
}
</pre>
<br />
Now, we are done with the first table too. <a href="http://blog.aunndroid.com/2011/11/learning-scala-boyermoore-search-3.html" target="_blank">Next</a> we will use these two tables to do the search.<br />
<br />
<b><u><i><span style="font-size: xx-small;"><div itemscope itemtype="http://data-vocabulary.org/Person">
Authored by <span itemprop="name">Win Myo Htet</span>
</div></span></i></u></b>
<b><u><i><span style="font-size: xx-small;"></span></i></u></b>
Win Myo Htethttp://www.blogger.com/profile/12932751895421525726noreply@blogger.com0tag:blogger.com,1999:blog-8495049179494016066.post-61678990840759864622011-11-17T17:58:00.000-08:002013-02-28T13:35:48.839-08:00Learning Scala : Boyer–Moore search 1
<b><u><i><span style="font-size: xx-small;"><div itemscope itemtype="http://data-vocabulary.org/Person">
Authored by <span itemprop="name">Win Myo Htet</span>
</div></span></i></u></b>
<br />
<b><u><span style="font-size: xx-small;"><br /></span></u></b>
I have been tipped off about Boyer-Moore for this Learning Scala series. Here is the <a href="http://en.wikipedia.org/w/index.php?title=Boyer%E2%80%93Moore_string_search_algorithm&oldid=461292434" target="_blank">wiki</a>. Basically, it tries to do the matching of the search string at the rear, thus if it does not match, it can hop the length of the search string. So, the longer the search string, the more efficient it is.<br />
<br />
As usual, the wiki will be our common reference. It is said that BM maintain two tables. The second table check if the character is in the search string or not. If the character is not in the search string at all, then, you can easily jump to the length of the search string. It also stores each character of the search string with the value which is the distance from the end of the string of the character.<br />
<br />
It is the first table that is quite complex to construct. I would recommend you to read again and again until you understand the construction of this table before you get to the code itself. This table will determine if the program will do proper thorough search without bugs or not. Let's try to dive into the first 4 rows of the table since the rest of the value is the same as the 4th row.<br />
<br />
<span style="font-family: "Georgia", "Times New Roman", serif;">(The current character inspected is in bold and next nearest possible match is underlined )</span><br />
Case : A<u><span style="font-family: "Georgia", "Times New Roman", serif;"><i>ANPANM<b>A</b>N</i></span></u><span style="font-family: "Georgia", "Times New Roman", serif;"> </span><br />
1st row. If the character is not N, it'd better be A or M or P. Otherwise, we will hop the length of the search string, which is 8, the length of the search string, according to the second table. So what is the minimum jump we can make, now that the character is not N. It has to be 1 jump to cover the possibility of the character being A. We assign the value 1 here.<br />
<br />
Case : ANPANM<b>PN</b><u><span style="font-family: "Georgia", "Times New Roman", serif;"><i>ANPANM</i></span></u><u><span style="font-family: "Georgia", "Times New Roman", serif;"><i>A</i></span></u><u><span style="font-family: "Georgia", "Times New Roman", serif;"><i>N</i></span></u><span style="font-family: "Georgia", "Times New Roman", serif;"> </span><br />
2nd row. Now that we have the last character matching N and get to the character before it, we have the case of string "<strike>A</strike>N". So if the character is not A, as usual, it'd better be M or N or P. Then, we have strings of "MN", "NN" and "PN". None of them are part of the actual search string "ANPANMAN". The value for not matching the needed character lead us to assign 8, the length of the search string. <br />
<br />
Case : AAA<u><span style="font-family: "Georgia", "Times New Roman", serif;"><i>AN<b>PAN</b>MAN</i></span></u><br />
3rd row. "<strike>M</strike>AN" means "AAN", "NAN" and "PAN". Of these, "PAN" is the sub string of our "AN<b>PAN</b>MAN". The wiki said that its jump value is 3. How do we get 3 ? We know that the matched P (which is <strike>M</strike>) from our current search position is 5. And P position in the search string is 2. We will subtract these values and we get 3.<br />
<br />
Case : "AAAA<b>AM</b><u><i><b>AN</b>PANMAN</i></u>"<br />
4th row. "<strike>N</strike>MAN" does not give us valid sub string. So, we will backtrack one more to look for the valid sub string, "<strike>N</strike><b>M</b><b>AN</b>", "<b>M</b><b>AN</b>", which is a substring of "ANPAN<b>MAN</b>". Our position of <b>M</b> in our search String is 5. The position of the first sub string of <b>MAN</b> in search string also is 5. If we do the difference, 5-5=0 and we are not making any jump. We don't want that! Let's backtrack one more time. <strike>"NM</strike><b>AN</b>", "<b>AN</b>" is a sub string of "<b>AN</b>P<b>AN</b>M<b>AN</b>". Our <b>A</b> position in sub string <strike>N</strike><strike>M</strike><b>A</b>N in our search is 6 and the position of the first sub string <b>AN</b> in <b>AN</b>PANMAN is 0. 6-0=6.<br />
<br />
If you have thus far followed me, good! Let's go over this table one more time!<br />
<br />
1st row redux. This is the first case and there are little info to do any sort of meaningful processing. We simply can assume that the value will always be 1.<br />
<br />
2nd row redux. This row is an odd one in the sequence of 1, 8, 3, 6, ... The jump value 8 is meaningful for the search string ANPANMAN, where <strike>A</strike>N is not a sub string of the search string,ANPANMAN . How about if these two characters string is a substring of the search string. For example, search String is ANPANMPN and our case is AAAAAA<u><b>AN</b>PANMPN</u>, where <strike>P</strike>N is AN. So, it is similar to 4th row above now. So, in this case, we will have have 6-0=6.<br />
<br />
Now that we have a bit of general pattern, we won't go over the rest of the row. The first row will always be 1. From 2nd and onward, we can do processing in a way that if the string of length 2 is not substring of the search string, the value will be the length of the search string, else we will always look for the difference of the position of the character in a current string to the position of the first valid sub string in the search string. If the difference is 0, we will backtrack the character and do the processing again. Now that we have analyzed what we can, let's try to put them into code <a href="http://blog.aunndroid.com/2011/11/learning-scala-boyermoore-search-2.html" target="_blank">next</a>.<br />
<br />
<b><u><i><span style="font-size: xx-small;"><div itemscope itemtype="http://data-vocabulary.org/Person">
Authored by <span itemprop="name">Win Myo Htet</span>
</div></span></i></u></b>
<b><u><i><span style="font-size: xx-small;"></span></i></u></b>
Win Myo Htethttp://www.blogger.com/profile/12932751895421525726noreply@blogger.com0tag:blogger.com,1999:blog-8495049179494016066.post-47218199038632377292011-11-14T16:44:00.000-08:002013-02-28T13:35:29.558-08:00Learning Scala : writing Quicksort the functional programming way<b><u><i><span style="font-size: xx-small;"><div itemscope itemtype="http://data-vocabulary.org/Person">
Authored by <span itemprop="name">Win Myo Htet</span>
</div></span></i></u></b>
<br />
<br />
The <a href="http://blog.aunndroid.com/2011/11/learning-scala-doing-scala-exercise.html" target="_blank">previous post</a> has been about doing Scala exercise from the Haskell example. Thus, the code is already written in the functional programming paradigm and I have just translated it into Scala language. To learn Scala and functional programming, we have to learn to think in the functional programming way. How do we do that? As usual, there is no easy way. We can only learn through getting our hands dirty by exercising through thinking in functional programming way.<br />
<br />
So, Quicksort has been picked for this exercise and the <a href="http://en.wikipedia.org/wiki/Quicksort" target="_blank">Quicksort wiki</a> will be used as a common reference. I will start implementing Quicksort in Scala by following the pseudo code described under the sub title "In-Place version". The Wiki has talked about some methods of choosing the pivot. However, it is not trivial to choose the pivot and it all depends on the set of data for the pivot-chooising-method to be meaningful. So, we will just pick the value of the first index of the array. Remember, the first value of the array can still be any value. So, here they are, very Java like.<br />
<br />
Partition method:<br />
<pre class="brush: scala">def partition(left : Int, right : Int, pivotIndex : Int, array : Array[Int]) : Int = {
val pivotValue = array(pivotIndex)
array(pivotIndex) = array(right)
array(right) = pivotValue
var storeIndex = left
for (i <- left until right) {
if (array(i) <= pivotValue) {
val temp = array(i)
array(i) = array(storeIndex)
array(storeIndex) = temp
storeIndex = storeIndex + 1
}
}
val temp2 = array(storeIndex)
array(storeIndex) = array(right)
array(right) = temp2
storeIndex
}
</pre>
<br />
quickSort method<br />
<pre class="brush: scala">def quickSort(left : Int, right : Int, array : Array[Int], direction : String = "begin") : Unit = {
if (left < right) {
val pivotIndex = 0
val newPivotIndex = partition(left, right, pivotIndex, array)
quickSort(left, newPivotIndex - 1, array, "left")
quickSort(newPivotIndex + 1, right, array, "right")
}
}</pre>
<br />
The codes are simply the implementation of the pseudo code. The only thing that differ from pseudo code might be that I have used the Scala's default argument variable for "direction" for debugging purpose.<br />
<br />
To be honest, I don't quite know how to re-implement this code into functional programming way. So, I have to get back to the basic abstract under sub title, "Algorithm".<br />
1. pick a pivot(done!)<br />
2. put a lesser value on the left, greater value on the right, put pivot where it belongs, which is between lesser and greater, of course.<br />
3. do the same process for lesser and greater by way of recursion.<br />
<br />
So how do we do step No. 2. Well, first, let's pick <i>List</i> as the data structure for our method since <i>List</i> is the preferred data structure when it comes to functional programming. The input will be <i>List</i>. Then, there are <i>lesser</i> and <i>greater </i>created based on the condition that the value of element of the List lesser(<) than pivot go to <i>lesser</i> List and the value of element of the List greater(>) than pivot go to <i>greater</i> List. How do we do that? We have to feed our variable <i>List</i> into some looping mechanism that will give us back two <i>List</i>s. <br />
<br />
From my experience with <a href="http://blog.aunndroid.com/2011/11/chewy-code-scala-tictactoe-part-1.html" target="_blank">Oleg's Tic Tac Toe code</a>. He makes use of <i>foldLeft</i> quite a lot. So, <i>folding</i> might be a solution? Yes, it is. If you read that blog on my understanding of the <i>folding</i> process, you will see that we can feed any collection into <i>folding</i> and can process the data for all kind of type of data as an end result. If you want to know how I come into this conclusion along with the thinking process, you need to read through that Tic Tac Toe blogs series.<br />
<br />
So, folding will be the looping mechanism. I have understood the <i>folding </i>process to involve <b><i>(foldLeftSeedValue,foldLeftElement)</i></b>. The <i><b>foldLeftSeedValue </b></i>will be our end result and we want it to be two <i>List</i>s namely: <i>lesser</i> and <i>greater</i>. So, the seed value has to be a tuple of two <i>List</i>s : <i>lesser</i> and <i>greater</i>. Then, we will do the matching on the conditions : <i>lesser</i> value will be added to the left <i>List</i> and <i>greater</i> value will be added to the right <i>List</i>. If you can visualize this far, that's good enough and let's look at the code.<br />
<br />
<pre class="brush: scala">def myQuickSort(list : List[Int]) : List[Int] = {
def myQuickSort(list : List[Int],
direction : String = "begin") : List[Int] = {
if (list.length <= 1) return list;
val pivot = list(0)
val pl = list.foldLeft(List[Int](), List[Int]()) {
case ((l, r), e) if e < pivot => (e :: l, r)
case ((l, r), e) if e > pivot => (l, e :: r)
case ((l, r), e) if e == pivot => (l :+ e, r)
case ((l, r), e) => println("Error processing : " + e);
sys.exit()
}
myQuickSort(pl._1.slice(0, pl._1.length - 1), "left")
++ List(pivot) ++ myQuickSort(pl._2, "right")
}
myQuickSort(list)
}</pre>
<br />
I have used nested method, which is not necessary, here. Let's get back to our <i>foldLeft</i> and <i>case</i> condition here. The first <i>case</i> line start with the form of <i><b>(foldLeftSeedValue,foldLeftElement)</b></i><i> </i>as expected<i>, foldLeftSeedValue </i>is<i> (l,r) tuple. </i><i>foldLeftElement </i>is<i> e</i>.<i> </i>Then if the condtion expression is met, the <i>foldLeftElement</i> is added to the head of the<i> list l</i> and the <i>(l,r) tuple</i> is passed on for the next iteration. The same can be said of the second match case. The third match case add the value to the end of the <i>list l</i>. The forth match is added because of the compiler warning that matching is not exhaustive. It makes me smile tho. :)<br />
<br />
Now, we have a tuple of two Lists: <i>l</i> being lesser and <i>r</i> being greater(on the right side of the pivot value). So we process the <i>lesser</i> and <i>greater</i> <i>List</i> the same way by means of iteration. We have to subtract one value from the lesser because we have added value equal to pivot at the end of the <i>lesser</i> list including the pivot itself. The pivot value has been put into a List which is placed between lesser and greater. The recursion will be exhausted when the list size is less than or equal 1. You know what's next.<br />
<br />
So, that's the end of my Quicksort in functional programming way in my own style(TM). However, you cannot count on me to write a truly efficient and fp style Quicksort because I am still a <a href="http://blog.aunndroid.com/2011/11/learning-scala-advice-of-exp-noob.html" target="_blank">noob</a>! Let's see how Quicksort is coded in Haskell land.<br />
<br />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code>quicksort :: Ord a => [a] -> [a]
quicksort [] = []
quicksort (p:xs) = (quicksort lesser) ++ [p] ++ (quicksort greater)
where
lesser = filter (< p) xs
greater = filter (>= p) xs
</code></pre>
<br />
Wow! Much way simpler! If it were not for Alan J. Perlis's wisdom: "<i>Simplicity does not precede complexity, but follows it.</i>", I would have shot myself! Let's look into this Haskell quicksort code. The detail analysis of this code can be found <a href="http://www.haskell.org/haskellwiki/Introduction" target="_blank">here</a> at section 3.1. The first line is method signature. The second line said that if the list is empty, return empty list. The third line syntax is a bit tricky. If you don't know that tricky syntax (along with the last line of <i>greater = ... </i>), you will think that there is a bug(I do think tho). If you were like me, you would have deduced that <i>p</i> is pivot. Good. <i>xs</i> is an input List. Hmm...<br />
<br />
If <i>xs</i> were input <i>List</i>, the resulting List size would have increased because in the last line, <i>greater</i> includes values equal to pivot while we are also manually adding pivot in a List in the middle of <i>lesser</i> and <i>greater</i>. Then, what is <i>xs</i>? Trust me, I am not Omniscience nor super genius. I have to ask my buddy! :D So, this Haskell buddy tells me that <i>xs</i> is a tail List and <i>p</i>(pivot) is the first element of the input List. Now, it all makes sense!<br />
<br />
Here is the Scala implementation of that QuickSort<br />
<br />
<pre class="brush: scala">def hsQuickSort(list : List[Int],
direction : String = "begin") : List[Int] = {
if (list.length <= 1) return list
val tail = list.tail
val pivot = list(0)
val lesser = (for { l <- tail
if l < pivot
} yield l).toList
val greater = (for { g <- tail
if g >= pivot
} yield g).toList
hsQuickSort(lesser, "lesser") ++ List(pivot)
++ hsQuickSort(greater, "greater")
}
</pre>
<br />
So, this has been my exercise on thinking in functional programming way. My original FP quicksort is not the most optimized nor simple but I can proudly say that it is my original. I would also encourage you to try to make yourself think and code in FP way. In the beginning, the code will be messy and inefficient but don't get discouraged. Jon Bentley, who gives talk on <a href="http://www.youtube.com/watch?v=aMnn0Jq0J-E" target="_blank">"Three Beautiful QuickSort"</a>, has mentioned of going over 11 versions to a piece of code to achieve the utmost simplicity. Cheer!<br />
<br />
<b><u><i><span style="font-size: xx-small;">Authored by Win Myo Htet</span></i></u></b>
<b><u><i><span style="font-size: xx-small;"></span></i></u></b>
<br />
<br />
<b><i>UPDATE</i></b><br />
<br />
<a href="http://en.wikipedia.org/wiki/Merge_sort" target="_blank">MergeSort</a><br />
<pre class="brush: scala">def mergeSort(list:List[Int]):List[Int]={
if(list.length<=1) return list
val mid=list.length/2
val left=mergeSort(list.slice(0,mid))
val right=mergeSort(list.slice(mid,list.length))
merge(left,right)
}
def merge(left:List[Int],right:List[Int]):List[Int]={
if(!left.isEmpty && right.isEmpty)return left
if(left.isEmpty && !right.isEmpty)return right
if(left.isEmpty && right.isEmpty)return List[Int]()
if(left(0)<=right(0)) return List(left(0))++merge(left.tail,right)
else return List(right(0))++merge(left,right.tail)
}</pre>
<br />
<a href="http://www.csc.depauw.edu/~bhoward/courses/0203Spring/csc122/haskintro/" target="_blank">Haskell MergeSort</a> <br />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code>merge [] ys = ys
merge xs [] = xs
merge (x:xs) (y:ys) = if x <= y
then x : merge xs (y:ys)
else y : merge (x:xs) ys
mergesort [] = []
mergesort [x] = [x]
mergesort xs = let (as, bs) = splitAt (length xs `quot` 2) xs
in merge (mergesort as) (mergesort bs)
</code></pre>
<br />
<br />
<br />
<b><u><i><span style="font-size: xx-small;"><div itemscope itemtype="http://data-vocabulary.org/Person">
Authored by <span itemprop="name">Win Myo Htet</span>
</div></span></i></u></b>
Win Myo Htethttp://www.blogger.com/profile/12932751895421525726noreply@blogger.com2tag:blogger.com,1999:blog-8495049179494016066.post-75438624404895831252011-11-06T00:05:00.000-07:002013-02-28T12:44:43.557-08:00Learning Scala: doing Scala exercise from Haskell's example
<b><u><i><span style="font-size: xx-small;">Authored by Win Myo Htet</span></i></u></b>
<br />
<br />
In my previous <a href="http://blog.aunndroid.com/2011/11/learning-scala-advice-of-exp-noob.html" target="_blank">post</a>, I complain about the lack of exercise from the Scala book for the learner to do exercise. So, I have been thinking of getting myself some exercise and talk with my friend who has inspired me to try functional programming. I have done the mandatory fizzbuzz interview on him regarding Haskell. I have updated his Haskell solution along with my Scala one in the previous <a href="http://blog.aunndroid.com/2011/11/learning-scala-advice-of-exp-noob.html" target="_blank">post</a>. I tell him about my plight and he blesses me with the following Haskell code from <a href="http://lisperati.com/haskell/ht3.html" target="_blank">here</a>.<br />
<br />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code>type Point = (Float,Float)
type Color = (Int,Int,Int)
type Polygon = [Point]
writePoint :: Point -> String
writePoint (x,y) = (show x)++","++(show y)++" "
writePolygon :: (Color,Polygon) -> String
writePolygon ((r,g,b),p) = "<polygon points=\""++(concatMap writePoint p)++"\" style=\"fill:#cccccc;stroke:rgb("++(show r)++","++(show g)++","++(show b)++");stroke-width:2\"/>"
writePolygons :: [(Color,Polygon)] -> String
writePolygons p = "<svg xmlns=\"http://www.w3.org/2000/svg\">"++(concatMap writePolygon p)++"</svg>"
colorize :: Color -> [Polygon] -> [(Color,Polygon)]
colorize = zip.repeat
rainbow@[red,green,blue,yellow,purple,teal] = map colorize [(255,0,0),(0,255,0),(0,0,255),(255,255,0),(255,0,255),(0,255,255)]
main = do
writeFile "tut0.svg" $ writePolygons (blue [[(100,100),(200,100),(200,200),(100,200)],
[(200,200),(300,200),(300,300),(200,300)]])
</code></pre>
<br />
The code has been modified to be able to compile as filename.hs. What does the code do? It creates a svg file, which draw a rectangluar with blue line. Since I have already provided the original link, I won't be going into it in detail. Let's try to implement our Scala equivalent.<br />
<br />
The first three lines of the Haskell code is pretty much class declaration in Scala with Polygon having a <i>List</i> of <i>Point</i>.<br />
<br />
In Haskell, the syntax structure for method is that method signature come first and then method body come next with leading method name. Haskell is space sensitive like Python. In method signature, <i>methodName::input->outPut</i> is the format.<br />
<br />
<i>writePoint </i>is getting the value of <i>Point</i> in <i>String</i> format and it is pretty much <i>Point</i>'s <i>toString. </i><br />
<br />
<i>writePolygon </i>is getting a <i>String</i> with the values of <i>Color</i> and <i>Polygon</i> embedded in some XML format. So basically, <i>Color</i> and <i>Polygon</i> does not have dedicated method like <i>Point</i> to print their value. Their values have been constructed in the line.<i><br />
</i><br />
<br />
<i>writePolygons </i>create the XML String with the parameter being <i>List</i> of <i>(Color,Polygon)</i> Tuple, which get feed into <i>writePolygon</i> individually for the respective XML string result.<br />
<br />
Ok, that's good enough to try some Scala, let's create three classes: <i>Point</i>, <i>Color</i> and <i>Polygon</i>. Since their values are always printed, we will override <i>toString</i> and return the desire format. It is straight forward to do that for <i>Point</i> and <i>Color</i>. <i>Polygon</i> has the <i>List</i> Collection of <i>Point</i> as its value and we will be using <i>foldRight</i> to print out the desire value. Now that overriding <i>toString</i> is done, we will just drop these object into our <i>writePolyGon</i> and <i>writePolyGons</i> method.<br />
<br />
That is easy. Here comes more interesting part. Before I start coding, when I was look at <i>colorize</i> and my friend asks me to read it, I said that it is <i>currying</i> and he said that it is correct. He said that the method definition's expression has dropped their parameter since it is inferred. Thus, <i>colorize=zip.repeat</i>. Now, I have to read a bit at the site to see what they do so that I know how to code them in Scala. It is said that <i>repeat</i> make use of Haskell's lazy pattern. Ok, it seems alright, Scala also has <i>lazy val</i>. Basically<i>, repeat </i>wait for the the next parameter <i>List</i> and create a new <i>List </i>of the size of the paramter <i>List </i>and fill it with the first parameter . <i>zip</i> zipps'em up these two. Sound good.<br />
<br />
I don't know <i>rainbow@</i> line. My friend is gone now. But it seems that it is a list of partial function, functional literal, created by <i>colorize </i>by having an initialize color value. I skip to the last line and read it and it appears so. Since, my Scala knowledge is quite <a href="http://blog.aunndroid.com/2011/11/chewy-code-scala-tictactoe-part-1.html" target="_blank">weak</a>, I don't recall anyway to emulate the Haskell's <i>rainbow@</i> line. (I will be very happy to learn if there is a way). So, I won't be having rainbow for now :( but <i>blue</i> only. So, let's see what I have done.<br />
<br />
<pre class="brush: scala">class Point(val x:Float,val y:Float){
override def toString()=x+","+y
}
class Color(val r:Int,val g:Int,val b:Int){
override def toString()=r+","+g+","+b
}
class Polygon(val pList:List[Point]){
override def toString()=pList.foldRight(""){(x,s)=>x+" "+s}
}
def writePolyGon(c:Color,p:Polygon):String="<polygon points=\""+p+"\" style=\"fill:#cccccc;stroke:rgb("+c+");stroke-width:2\"/>"
def writePolyGons(tList:List[(Color,Polygon)]):String
={"<svg xmlns=\"http://www.w3.org/2000/svg\">"+
tList.foldLeft(""){(s,x)=>s+writePolyGon(x._1,x._2)}+
"</svg>"
}
def colorize(c:Color)(pList:List[Polygon]):List[(Color,Polygon)]
={
lazy val repeat=(for(p<-pList)yield(c,p)).toList
repeat
}
val blue=new Color(0,0,255)
val blue_ = colorize(blue)_
val rectangle1=new Polygon(List(new Point(100,100),new Point(200,100),new Point(200,200),new Point(100,200)))
val rectangle2=new Polygon(List(new Point(200,200),new Point(300,200),new Point(300,300),new Point(200,300)))
printToFile("tut0ofScala.svg",writePolyGons(blue_((List(rectangle1,rectangle2)))))
def printToFile(fileName:String, content:String):Unit
={printToFile(new java.io.File(fileName))(p=>p.println(content))}
/*http://stackoverflow.com/questions/4604237/how-to-write-to-a-file-in-scala*/
def printToFile(f :java.io.File)(op : java.io.PrintWriter => Unit)
={ val p=new java.io.PrintWriter(f)
try{ op(p)} finally{p.close()}
}
</pre>
<br />
I have created 2 rectangle objects instead of feeding non descriptive data. Scala not having the file writing mechanism as part of the standard library does not also help. I have to run to SO for that as it can be seen in the comment line. Definitely, my Scala code will have a lot of room for improvement and I sure want to learn them.<br />
<br />
<br />
<br />
<b><u><i><span style="font-size: xx-small;">Authored by Win Myo Htet</span></i></u></b>
<b><u><i><span style="font-size: xx-small;"></span></i></u></b>
Win Myo Htethttp://www.blogger.com/profile/12932751895421525726noreply@blogger.com10