Showing posts with label Basic. Show all posts
Showing posts with label Basic. Show all posts

Saturday, May 12, 2012

Scala Cheat Sheet

Scala Cheat Sheethttp://www.scala-lang.org/docu/files/ScalaOverview.pdf

Since it's hard to search for scala syntactic constructions, hopefully this page might help
Note language coverage is incomplete. 
Source on github, pull requests welcome! 
Update: A version of this is now in the Scala documentation.



read more...

Wednesday, May 9, 2012

Scala - Files I/O


Scala is open to make use of any Java objects and java.io.File is one of the object which can be used in Scala programming to read and write files. Following is an example of writing to a file:
import java.io._

object Test {
   def main(args: Array[String]) {
      val writer = new PrintWriter(new File("test.txt" ))

      writer.write("Hello Scala")
      writer.close()
   }
}
When the above code is compiled and executed, it creates a file with "Hello Scala" content which you can check yourself.
C:/>scalac Test.scala
C:/>scala Test

C:/>

Reading line from Screen:

Sometime you need to read user input from the screen and then proceed for some further processing. Following example shows you how to read input from the screen:
object Test {
   def main(args: Array[String]) {
      print("Please enter your input : " )
      val line = Console.readLine
      
      println("Thanks, you just typed: " + line)
   }
}
When the above code is compiled and executed, it prompts you to enter your input and it continues until you press ENTER key.
C:/>scalac Test.scala
C:/>scala Test
scala Test
Please enter your input : Scala is great
Thanks, you just typed: Scala is great

C:/>

Reading File Content:

Reading from files is really simple. You can use Scala's Source class and its companion object to read files. Following is the example which shows you how to read from "test.txt" file which we created earlier:
import scala.io.Source

object Test {
   def main(args: Array[String]) {
      println("Following is the content read:" )

      Source.fromFile("test.txt" ).foreach{ 
         print 
      }
   }
}
When the above code is compiled and executed, it will read test.txt file and display the content on the screen:
C:/>scalac Test.scala
C:/>scala Test
scala Test
Following is the content read:
Hello Scala

C:/>



[tutorialspoint]
read more...

Scala - Extractors


An extractor in Scala is an object that has a method called unapply as one of its members. The purpose of that unapply method is to match a value and take it apart. Often, the extractor object also defines a dual method apply for building values, but this is not required.
Following example shows an extractor object for email addresses:
object Test {
   def main(args: Array[String]) {
      
      println ("Apply method : " + apply("Zara", "gmail.com"));
      println ("Unappy method : " + unapply("Zara@gmail.com"));
      println ("Unappy method : " + unapply("Zara Ali"));

   }
   // The injection method (optional)
   def apply(user: String, domain: String) = {
      user +"@"+ domain
   }

   // The extraction method (mandatory)
   def unapply(str: String): Option[(String, String)] = {
      val parts = str split "@"
      if (parts.length == 2){
         Some(parts(0), parts(1)) 
      }else{
         None
      }
   }
}
This object defines both apply and unapply methods. The apply method has the same meaning as always: it turns Test into an object that can be applied to arguments in parentheses in the same way a method is applied. So you can write Test("Zara", "gmail.com") to construct the string "Zara@gmail.com".
The unapply method is what turns Test class into an extractor and it reverses the construction process of apply. Where apply takes two strings and forms an email address string out of them, unapply takes an email address and returns potentially two strings: the user and the domain of the address.
The unapply must also handle the case where the given string is not an email address. That's why unapply returns an Option-type over pairs of strings. Its result is either Some(user, domain) if the string str is an email address with the given user and domain parts, or None, if str is not an email address. Here are some examples:
unapply("Zara@gmail.com") equals Some("Zara", "gmail.com")
unapply("Zara Ali") equals None
When the above code is compiled and executed, it produces following result:
C:/>scalac Test.scala
C:/>scala Test
Apply method : Zara@gmail.com
Unappy method : Some((Zara,gmail.com))
Unappy method : None

C:/>

Pattern Matching with Extractors:

When an instance of a class is followed by parentheses with a list of zero or more parameters, the compiler invokes the apply method on that instance. We can define apply both in objects and in classes.
As mentioned above, the purpose of the unapply method is to extract a specific value we are looking for. It does the opposite operation apply does. When comparing an extractor object using the match statement the unapply method will be automatically executed as shown below:
object Test {
   def main(args: Array[String]) {
      
      val x = Test(5)
      //apply is invoked... the value 10 is returend
      println(x)

      x match
      {
         case Test(num) => println(x+" is bigger two times than "+num)
         //unapply is invoked
         case _ => println("i cannot calculate")
      }

   }
   def apply(x: Int) = x*2
   def unapply(z: Int): Option[Int] = if (z%2==0) Some(z/2) else None
}
When the above code is compiled and executed, it produces following result:
C:/>scalac Test.scala
C:/>scala Test
10
10 is bigger two times than 5

C:/>



[tutorialspoint]
read more...

Scala - Exception Handling


Scala's exceptions works like exceptions in many other languages like Java. Instead of returning a value in the normal way, a method can terminate by throwing an exception. However, Scala doesn't actually have checked exceptions.
When you want to handle exceptions you use a try{...}catch{...} block like you would in Java except that the catch block uses matching to identify and handle the exceptions.

Throwing exceptions:

Throwing an exception looks the same as in Java. You create an exception object and then you throw it with the throw keyword:
throw new IllegalArgumentException

Catching exceptions:

Scala allows you to try/catch any exception in a single block and then perform pattern matching against it using case blocks as shown below:
import java.io.FileReader
import java.io.FileNotFoundException
import java.io.IOException

object Test {
   def main(args: Array[String]) {
      try {
         val f = new FileReader("input.txt")
      } catch {
         case ex: FileNotFoundException =>>{
            println("Missing file exception")
         }
         case ex: IOException => {
            println("IO Exception")
         }
      }
   }
}
When the above code is compiled and executed, it produces following result:
C:/>scalac Test.scala
C:/>scala Test
Missing file exception

C:/>
The behavior of this try-catch expression is the same as in other languages with exceptions. The body is executed, and if it throws an exception, each catch clause is tried in turn.

The finally clause:

You can wrap an expression with a finally clause if you want to cause some code to execute no matter how the expression terminates.
import java.io.FileReader
import java.io.FileNotFoundException
import java.io.IOException

object Test {
   def main(args: Array[String]) {
      try {
         val f = new FileReader("input.txt")
      } catch {
         case ex: FileNotFoundException => {
            println("Missing file exception")
         }
         case ex: IOException => {
            println("IO Exception")
         }
      } finally {
         println("Exiting finally...")
      }
   }
}
When the above code is compiled and executed, it produces following result:
C:/>scalac Test.scala
C:/>scala Test
Missing file exception
Exiting finally...

C:/>



[tutorialspoint]
read more...

Scala - Regular Expressions


Scala supports regular expressions through Regex classe available in the scala.util.matching package. Let us check an example where we wil try to find out word Scala from a statement:
import scala.util.matching.Regex

object Test {
   def main(args: Array[String]) {
      val pattern = "Scala".r
      val str = "Scala is Scalable and cool"
      
      println(pattern findFirstIn str)
   }
}
When the above code is compiled and executed, it produces following result:
C:/>scalac Test.scala
C:/>scala Test
Some(Scala)

C:/>
We create a String and call the r( ) method on it. Scala implicitly converts the String to a RichString and invokes that method to get an instance of Regex. To find a first match of the regular expression, simply call the findFirstIn() method. If instead of finding only the first occurrence we would like to find all occurrences of the matching word, we can use thefindAllIn( ) method and in case there are multiple Scala words available in the target string, this will return a collection of all matching words.
You can make use of the mkString( ) method to concatenate the resulting list and you can use a pipe (|) to search small and capital case of Scala and you can use Regex constructor instead orr() method to create a pattern as follows:
import scala.util.matching.Regex

object Test {
   def main(args: Array[String]) {
      val pattern = new Regex("(S|s)cala")
      val str = "Scala is scalable and cool"
      
      println((pattern findAllIn str).mkString(","))
   }
}
When the above code is compiled and executed, it produces following result:
C:/>scalac Test.scala
C:/>scala Test
Scala,scala

C:/>
If you would like to replace matching text, we can use replaceFirstIn( ) to replace the first match or replaceAllIn( ) to replace all occurrences as follows:
object Test {
   def main(args: Array[String]) {
      val pattern = "(S|s)cala".r
      val str = "Scala is scalable and cool"
      
      println(pattern replaceFirstIn(str, "Java"))
   }
}
When the above code is compiled and executed, it produces following result:
C:/>scalac Test.scala
C:/>scala Test
Java is scalable and cool

C:/>

Forming regular expressions:

Scala inherits its regular expression syntax from Java, which in turn inherits most of the features of Perl. Here are just some examples that should be enough as refreshers:
Here is the table listing down all the regular expression metacharacter syntax available in Java:
SubexpressionMatches
^Matches beginning of line.
$Matches end of line.
.Matches any single character except newline. Using m option allows it to match newline as well.
[...]Matches any single character in brackets.
[^...]Matches any single character not in brackets
\\ABeginning of entire string
\\zEnd of entire string
\\ZEnd of entire string except allowable final line terminator.
re*Matches 0 or more occurrences of preceding expression.
re+Matches 1 or more of the previous thing
re?Matches 0 or 1 occurrence of preceding expression.
re{ n}Matches exactly n number of occurrences of preceding expression.
re{ n,}Matches n or more occurrences of preceding expression.
re{ n, m}Matches at least n and at most m occurrences of preceding expression.
a|bMatches either a or b.
(re)Groups regular expressions and remembers matched text.
(?: re)Groups regular expressions without remembering matched text.
(?> re)Matches independent pattern without backtracking.
\\wMatches word characters.
\\WMatches nonword characters.
\\sMatches whitespace. Equivalent to [\t\n\r\f].
\\SMatches nonwhitespace.
\\dMatches digits. Equivalent to [0-9].
\\DMatches nondigits.
\\AMatches beginning of string.
\\ZMatches end of string. If a newline exists, it matches just before newline.
\\zMatches end of string.
\\GMatches point where last match finished.
\\nBack-reference to capture group number "n"
\\bMatches word boundaries when outside brackets. Matches backspace (0x08) when inside brackets.
\\BMatches nonword boundaries.
\\n, \\t, etc.Matches newlines, carriage returns, tabs, etc.
\\QEscape (quote) all characters up to \\E
\\EEnds quoting begun with \\Q

Regular-expression Examples:

ExampleDescription
.Match any character except newline
[Rr]ubyMatch "Ruby" or "ruby"
rub[ye]Match "ruby" or "rube"
[aeiou]Match any one lowercase vowel
[0-9]Match any digit; same as [0123456789]
[a-z]Match any lowercase ASCII letter
[A-Z]Match any uppercase ASCII letter
[a-zA-Z0-9]Match any of the above
[^aeiou]Match anything other than a lowercase vowel
[^0-9]Match anything other than a digit
\\dMatch a digit: [0-9]
\\DMatch a nondigit: [^0-9]
\\sMatch a whitespace character: [ \t\r\n\f]
\\SMatch nonwhitespace: [^ \t\r\n\f]
\\wMatch a single word character: [A-Za-z0-9_]
\\WMatch a nonword character: [^A-Za-z0-9_]
ruby?Match "rub" or "ruby": the y is optional
ruby*Match "rub" plus 0 or more ys
ruby+Match "rub" plus 1 or more ys
\\d{3}Match exactly 3 digits
\\d{3,}Match 3 or more digits
\\d{3,5}Match 3, 4, or 5 digits
\\D\\d+No group: + repeats \\d
(\\D\\d)+/Grouped: + repeats \\D\d pair
([Rr]uby(, )?)+Match "Ruby", "Ruby, ruby, ruby", etc.
Note that, every backslash appears twice in the string above. This is because in Java and Scala a single backslash is an escape character in a string literal, not a regular character that shows up in the string. So instead of .\. you need to write .\\. to get a single backslash in the string. Check the following example:
import scala.util.matching.Regex

object Test {
   def main(args: Array[String]) {
      val pattern = new Regex("abl[ae]\\d+")
      val str = "ablaw is able1 and cool"
      
      println((pattern findAllIn str).mkString(","))
   }
}
When the above code is compiled and executed, it produces following result:
C:/>scalac Test.scala
C:/>scala Test
able1

C:/>



tutorialspoint
read more...