functional programming with scala

Download Functional programming with Scala

If you can't read please download the document

Upload: neelkanth-sachdeva

Post on 20-Aug-2015

909 views

Category:

Technology


5 download

TRANSCRIPT

  1. 1. Functional Programming with ScalaNeelkanth SachdevaConsultantKnoldus Software LLPneelkanthsachdeva.wordpress.com
  2. 2. Programming LanguagesOne approach to the software crisis is to introduce newprogramming languages that supports following :Reusability Clear , Concise and High performance code. Rapid prototyping Reduces time and cost for development
  3. 3. Why Scala ?
  4. 4. Scala programming languageBorn from the mind of Martin Odersky.A good mix of : Object orientation functional programming A powerful type system code Eligent and powerful code then otherlanguages
  5. 5. Scala features :
  6. 6. Scala attempts to blend three dichotomies of thought into one language. These are: Functional programming and object-oriented programming Expressive syntax and static typing Advanced language features and rich Javaintegration Let us understand these one-by-one :-
  7. 7. Functional programming and object oriented programming Functional programming is style of programming in which the basic method of computation is the application of functions to arguments. Functional programming puts special emphasis on the verbs of a program & Object-oriented programming puts special emphasis on nouns and attaches verbs to them. The two approaches are almost inverses of each other, with one being top down and the other bottom up. Functional programming approaches software as the combination and application of functions. It tends to decompose software into behaviors, or actions that need to be performed, usually in a bottom-up fashion.
  8. 8. Didnt understood...Have a look ?Scenerio : A Lion catches a deer and eats it. The OOPS approach :class Deerclass Lion { def catch(d: Deer): Unit = ... def eat(): Unit = ... } val lion = new Lion val deer = new Deer lion.catch(deer)lion.eat()
  9. 9. Functional programming approachtrait Liontrait Deertrait Catchtrait FullTummydef catch(hunter: Lion, prey: deer): Lion with Catchdef eat(consumer: Lion with Catch): Lion with FullTummyval story = (catch _) andThen (eat _)story(new Lion, new Deer)
  10. 10. Static typing and expressivenessThe Scala type system allows expressive code. Scala made a few simple design decisions that help make it expressive:- Changing sides of type annotation- Type inference- Scalable syntax- User-defined implicits
  11. 11. Transparently working with the JVM Seamless integration with Java and the JVM Using Java libraries from Scala is seamlessbecause Java idioms map directly into Scalaidioms. libraries written in Java can be imported into Scala as is.
  12. 12. RecursionRecursion plays a larger role in pure functionalprogramming than in imperative programming, in partbecause of the restriction that variables are immutable.For example, you cant have loop counters, which wouldchange on each pass through a loop. One way toimplement looping in a purely functional way is withrecursion.Lets have a look :Calculating factorials provides a good example. Here is animperative loop implementation.
  13. 13. Imperative loop implementationdef factorialWithLoop(i: BigInt): BigInt = { var resultantValue = BigInt(1) for (h i * factorial_Functional(i - 1) }for (i def findAnInt(implicit x : Int) = xfindAnInt: (implicit x: Int)Intscala> findAnInt:7: error: could not find implicit value for parameter x: IntfindAnInt^
  14. 16. The findAnInt method is called without specifying anyargument list. The compiler complains that it cant find animplicit value for the x parameter. Well provide one, asfollows:scala> implicit val test = 5test: Int = 5scala> findAnIntres3: Int = 5
  15. 17. Avoid call site evaluation ?Sometimes we want arguments not be evaluated at call site :def executeMe(msgString: () => String) {println(msgString())}Now calling the method like :executeMe(() => "This" + " is" + " not"+ " looking" + "good!")Not looking good...isnt it?
  16. 18. How we can do this in a good way :We can use => in a type annotation to define a by-name parameter.// by-name parameter def iAmOk(msgString: => String) { println(msgString) }Now calling it as :/* * Using by-name Parameter */ iAmOk("This" + " is" + " an" + " use"+" case"+ " by-name" + " param.")
  17. 19. Partial Functions : Need not be defined on its whole domain PartialFunction is a subtype of Function1: trait PartialFunction [-A, +B] extends A => B Use isDefinedAt to determine whether a partial function is defined for a given value or not.
  18. 20. Using isDefinedAt :object KnolXPartialFunction {// defined a mapval KnolXMap = Map(1 -> "Neelkanth", 2 -> "Sachdeva")def main(args: Array[String]) {val booleanAnswer1 = KnolXMap.isDefinedAt(1)println("The Answer is " + booleanAnswer1)val booleanAnswer2 = KnolXMap.isDefinedAt(3)println("The Answer is " + booleanAnswer2)}}Output should be as :The Answer is trueThe Answer is false
  19. 21. Use a block of case alternatives to define apartial function literal :scala> (a to f).zipWithIndex filter {| case (_, i) => i % 2 == 0|}Result should be like this :res0: ... = Vector((a,0), (c,2), (e,4))
  20. 22. Using the right collection The Scala collections library is the single most impressive library in the Scala ecosystem. The Scala collections provide many ways of storing and manipulating data, which can be overwhelming. Because most of the methods defined on Scala collections are available on every collection. Scalas collections also split into three dichotomies: Immutableand mutable collections Eager and delayed evaluation Sequential and parallel evaluation
  21. 23. The collection hierarchyTraversable : The Traversable trait is defined in terms of theforeach method.This method is an internal iterator---that is, theforeach method takes a function that operates on a singleelement of the collection and applies it to every element of thecollection. Travers-able collections dont provide any way tostop traversing inside the foreach.Iterable : The Iterable trait is defined in terms of the iteratormethod. This returns an external iterator that you can use towalk through the items in the collection.scala> val names = Iterable("Josh", "Jim")names: Iterable[java.lang.String] = List(Josh, Jim)
  22. 24. Seq : The Seq trait is defined in terms of the length and apply method. It represents collections that have a sequential ordering. We can use the apply method to index into the collection by its ordering. The length methodreturns the size of the collection.scala> val x = Seq(2,1,30,-2,20,1,2,0)x: Seq[Int] = List(2, 1, 30, -2, 20, 1, 2, 0)scala> x.tails map (_.take(2)) filter (_.length > 1)map (_.sum) toListres0: List[Int] = List(3, 31, 28, 18, 21, 3, 2)
  23. 25. LinearSeq: The LinearSeq trait is used to denote that acollection can be split into a head and tail component.IndexedSeq: The IndexedSeq trait is similar to the Seq traitexcept that it implies that random access of collectionelements is efficient that is, accessing elements of acollectionshould be constant or near constant.scala> val x = IndexedSeq(1, 2, 3)x: IndexedSeq[Int] = Vector(1, 2, 3)scala> x.updated(1, 5)res0: IndexedSeq[Int] = Vector(1, 5, 3)SetMap
  24. 26. Some special & powerful collection methods: sliding : Groups elements in fixed size blocks by passing asliding window over them . Curried methods : A method can have more than one parameter list, which is called currying2 . foldLeft : foldLeft transforms a collection into a single value.
  25. 27. Using sliding method :object KnolXSliding {def KnolXSlide = {1 to 6 sliding 4 foreach println}def main(args: Array[String]) {// Call the sliding methodKnolXSlide}}Output should be :Vector(1, 2, 3, 4)Vector(2, 3, 4, 5)Vector(3, 4, 5, 6)