Posts

Showing posts with the label Scala

Pattern matching Explained

Image
This is an explanation to the previous blog 1 relating to the Scala Matching. Most of the thoughts referring to the book "Functional Programming in Scala" 2 . For example consider the following Algebraic Data Type MList: // Singly linked lists sealed trait MList[+A] case object MNil extends MList[Nothing] case class Cons[+A](head:A, tail: MList[A]) extends MList[A] object MList{ //companion object def sum (ints: MList[Int]):Int = ints match { case MNil => 0 case Cons(x,xs) => x + sum(xs) } def apply[A](as: A*): MList[A] = if (as.isEmpty) MNil else Cons(as.head, apply(as.tail: _*)) def append[A](fs:MList[A], ss:MList[A]): MList[A] = fs match { case MNil => ss case Cons(h,t) => Cons(h,append(t, ss)) } //curried way def dropWhile[A](l:MList[A])( f:A => Boolean): MList[A] = l match { case Cons(h,t) if f(h) => dropWhile(t)(f) case _ => l } } val x : MList[Int] = MList() val y :...

Scala Functions

Local Functions Local functions are the functions defined inside other functions. Therefore , local functions can access the parameters of their enclosing function. First-class Functions Scala supports first-class functions which can be user defined as well as anonymous literal value, for example (x:Int) => x + 1 parameters and the function body separated by the "=>". In case if the type can be inference, then no need to define type, this is called target typing . In the partially applied function , no need to provide all the necessary parameters, but partially. For example, def sum(a:Int, b:Int):Int = a + b //> sum: (a: Int, b: Int)Int val a = sum _ //> a : (Int, Int) => Int = ex3$$$Lambd a.apply(1,2) //> res1: Int = 3 In the second line, you don't need to give parameters. The underscore can be given to replace one or more parameters: val f: (Int, I...

Scala Tips - separating common from varying

It is a best practice to separating common from varying in the Scala. Common parts are implemented as functions and the varying parts will be arguments: def createSeqOnCriteria(start:Int, end:Int, // createSeqOnCriteria: createSeqOnCriteria[](val start: Int,val end: Int,val criteria: Int => Boolean) => scala.collection.immutable.IndexedSeq[Int] criteria: Int => Boolean) = { // for (i <- start to end if criteria(i)) yield i // } // ...

Scala Tips: Functions and Closures

Image
In the Scala functions are first class. For example function literal can be possible to assign to object as follows: val f = (x:Int ) => x + x //f: Int => Int = <function1> f(2) // res0: Int = 4 The different between function literal and function value is that literal exists in source code and the value exists in the runtime. Compiler do the target typing if you don't specify the type for the x in the above source. To more precise, you can use the _ as a placeholder instead of x bound variable in the above code because x is a parameter to the function. For simplicity : //collection supports val l1 = for (i <- 1 to 10) yield i //l1: scala.collection.immutable.IndexedSeq[Int] = Vector(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) l1.filter(_ > 3 ) //res1: scala.collection.immutable.IndexedSeq[Int] = Vector(4, 5, 6, 7, 8, 9, 10) In the above source, when _ used that is called partially applied function because don't supply all of the arguments needed by the expre...

Scala Tips: Matching

Scala matching functionality is compelling. This feature is very important for big data programming. This blog tries to consolidate matching example as much as possible. Basic use of Match Boolean operator Use in the exceptions With Constants With Regex With Vector With Map As an Iterator Case with guard conditions With Option With Tuples With List With Seq Wildcards Case classes Reference Basic use of Match The simplest matching var i = 2 // i: Int = 2 // i match { // res0: String = two case 1 => "one" // case 2 => "two" // } // You can match anything as follows: def getClassAsString(x: Any):String = x match { // getClassAsString: (x: Any)String case s: String => s + " is a string" // case i: Int => i +" is Int" ...

SBT fundamentals

To install the SBT in the Mac environment brew install sbt@1 Say you have a following run.scala file in your directory, package world object Hello extends App { print("Hello World") } now start the sbt and run the compile command first, after that runMain world.Hello Now you can have a build.sbt file as follows name := "Greetings" organization := "ojitha.blogspot.com.au" version := "1.0.0" To show resolvers show resolvers To show dependencies show libraryDependencies To publish locally publishLocal You can add the dependencies as follows to the build.sbt name := "Greetings" organization := "ojitha.blogspot.com.au" version := "1.0.0-SNAPSHOT" resolvers += "Sonatype releases repo" at "https://oss.sonatype.org/content/repositories/Releases" { val liftVersion = "3.1.0" libraryDependencies ++= List( "net.liftweb" %% "lift-util...

Scala Tips: case class

Image
The case class is one of the most important for data wrangle . Here some use of the case class using Scala comprehensions such as for comprehension. Here the implementation:  case class Member (name: String, age: Int) // defined class Member case class Family (members: Seq[Member]) // defined class Family // ...

Intellij Idea for Scala

I am using IntelliJ more than 5 years now and eventually became a fan of that. I used both Ultimate edition and community edition. The community edition Scala plugin is well established now compared to 2 years back. However, there are a number of important productivity topics to discuss here. Copy Scala worksheet For example, I want to copy the Scala worksheet to the text editor sublime. Here the steps you need to follow 1. in the IntelliJ, enable column selection mode by CMD+SHIFT+8 2. Select the text you want to copy (for example first the left side of the split screen where Scala source is available) 3. Paste the copied text sublime new file CMD + N 4. In the Sublime now press the CMD + OPTION + F to search and replace. 5. Enable the regex, and search the $ (end of the line) and replace <space>//<space> and click the replace all. 6. Now back to the IntelliJ Idea and selecting the other side ( right side of the split screen where the results are) after CMD+SH...

Scala Notes

Maps Here the example of Map and the immutable map. import java.net.URL import java.util.Scanner val in = new Scanner( new URL( "https://raw.githubusercontent.com/rdwallis/alice/master/src/main/webapp/WEB-INF/book/10.txt" ).openStream()) var count = Map[String, Int]() //var count = scala.collection.mutable.Map[String, Int]() while (in.hasNext()){ val word = in.next() count.+=(word->(count.getOrElse(word, 0 )+ 1 )) //count(word) = count.getOrElse(word,0)+1 } count( "Alice" ) Above code segment, mutable Map is commented. This is an exercise I did from the Scala for the Impatient .