Modern Functional Programming and Actors with Scala and Akka
Total Page:16
File Type:pdf, Size:1020Kb
Modern Functional Programming and Actors With Scala and Akka Aaron Kosmatin Computer Science Department San Jose State University San Jose, CA 95192 707-508-9143 [email protected] Abstract sons for this. Functional programming languages place a strong emphasis on minimization of side ef- For many years, functional programming has had fects, and immutable states. Functional program- an academic presence in computer science, but ming is an expansion of lambda calculus. The has been poorly represented in popular languages. idea of functional programming is that the pro- Functional programming has been making a resur- gram executes as a series of mathematical func- gence lately. With Java 8, Oracle has introduced tion evaluations[2]. From its mathematical nature, lambda functions, an essential part of functional every function call that has the same arguments programming, to Java. Much of the resurgent in- should produce the same return statement. terest in functional programming originates with Martin Odersky, designer of Scala and Co-founder of Typesafe. The Actor Model of concurrent programming The emphasis on reduction of side effects has pre-dates Scala, with implementations in languages hurt the adoption of functional languages in the such as Erlang, but has been an underutilized industry, many programs require some form of side model. The Actor Model is well adapted to multi- effect. Side effects include any modification of a core and multi-machine programming. The Actor state, such as modifying a variable, printing to the Model has regained interest recently due to the console and writing to files. As well, for many pro- work of Jonas Bon´er,developer of the Akka Ac- grammers, it is easier to conceptualize problems by tor library for Java and Scala and Co-founder of modifying states. Typesafe. Scala and Akka actors provide developers with well developed tools for parallel and distributed computing. Due to the tools available with the While there are drawbacks to functional pro- Typesafe platform, Scala and Actors have become gramming, there are two important advantages. a core part of the technology stack at companies First, functional code tends to be easier to read like Twitter, LinkedIn, and Netflix. and maintain between programmers. By its na- ture, functional programming has few mutable vari- ables. It is not required for a programmer to track 1 Functional Programming how a variable is changing through the execution of the code. Second, with its emphasis on immutabil- Functional programming has not seen wide use in ity, functional programming tends to be much more the programming industry. There are several rea- parallelizable. 1 1 o b j e c t VarValDeclarations f 1 o b j e c t firstClassFunctions f 2 vara=1 2 d e f f(x: Int) =x+ 2; 3 v a lb=2 3 p r i n t l n(Array(1,2,3).map(f)) 4 v a l c:Int=3 4 g 5 d e f aFunction(value:Int):Int = f 6 value Output: 7 g 8 d e f bFunction(value:Any) = f Array(3, 4, 5) 9 value 10 g 11 g Figure 2: First class functions in Scala Figure 1: Variable and Value declarations Scala collections. By default the members of a col- lection are immutable, unless a mutable collection 2 Scala is imported by the programmer. A last thing to notice in figure 1 is that the Traditionally, Object oriented programming has functions do not have an explicit return statement. been a subset of procedural languages, with lan- Scala does support the return keyword, but will de- guages like C++ and Java. In 2003, Martin fault to returning the last line of a function block. Odersky developed Scala for his programming lan- This makes sense given Scala's functional influence. guage class at Ecole´ Polytechnique F´ed´erale de Function's with no return, or void functions, are Lausanne[1]. He wanted to show that object ori- used to create side effects, but since functional lan- ented programming was compatible with functional guages try to eliminate side effects, every function programming. should have a return value. Strictly speaking, Scala is not a functional pro- Figure 2 shows how functions can be used as first gramming language, nor is it a procedural lan- class objects in Scala. This is a standard feature of guage. Scala fully supports both forms of program- functional programming, where a functions can be ming. Scala is built on top of the JVM, and com- used in the same manner as other types. In this piles to Java bytecode. As such, Scala is compatible example, the function f is used as an argument to with Java libraries, and Scala libraries are compat- the map function[3]. ible with Java. Scala addresses one of the limiting As can be seen from figure 3, Scala and Java factors of previous functional languages, in that it are similar. One important difference is that unlike allows the programmer to use procedural program- Java, Scala supports the Singleton Design Pattern ming when required. at the language level. In Scala, an object is a single- ton. Since Scala is object oriented, it also supports 2.1 Scala Language Basics classes and an object hierarchy like Java's. Scala has a philosophy of offloading much of the 2.2 For Yield Condition/Map Filter typing to the compiler. Like Java, Scala is a strongly typed language, but the type is usually Scala supports functional constructs, such as maps. inferred by the compiler at compile time. Lines 3 In figures 4, 5 and 6 show examples of Scala's for- and 4 of figure 1 show the declaration of two inte- yield syntax. In figure 4, maps are used to generate gers. On line 3, the type is inferred by the compiler, a cartesian product. In figure 5, a for-yield state- and on line 4, the type is explicitly set by the pro- ment is used. At compilation, the code in figure 5 grammer. is converted into code similar to figure 4, however, Scala also supports variables and values. Vari- depending on the situation, one may be more read- ables work as expected from other languages. Val- able than the other[4]. In figure 6, a condition is ues are the immutable variant of variables. Scala, added to the for statement, removing symmetric in general, prefers immutable objects. An exam- results. A similar condition can be applied to the ple of Scala's preference for immutability is in the map syntax. 2 Listing 1: Java Hello World Listing 2: Scala Hello World 1 p u b l i c class HelloJava f 1 o b j e c t HelloScala f 2 public static void main(String[] 2 d e f main(args: Array[String]) f a r g s ) f 3 p r i n t l n("Hello Scala") 3 System.out.println("Hello Java"); 4 g 4 g 5 g 5 g Figure 3: Hello Worlds in Scala and Java Listing 3: Sequential Loop Execution Listing 4: Parallel Loop Execution 1 o b j e c t ParallelExample extends Appf 1 o b j e c t ParallelExample extends Appf 2 v a l integers=1 until5 2 v a l integers=1 until5 3 v a l timesTable=for(integer1 <− 3 v a l timesTable=for(integer1 <− i n t e g e r s ) yield f integers .par) yield f 4 f o r(integer2 <− i n t e g e r s ) yield f 4 f o r(integer2 <− i n t e g e r s ) yield f 5 i n t e g e r 1 ∗ i n t e g e r 2 5 i n t e g e r 1 ∗ i n t e g e r 2 6 g 6 g 7 g 7 g 8 timesTable. foreach(println( )) 8 timesTable. foreach(println( )) 9 g 9 g Output: Output: Vector(1, 2, 3, 4) Vector(1, 2, 3, 4) Vector(2, 4, 6, 8) Vector(2, 4, 6, 8) Vector(3, 6, 9, 12) Vector(4, 8, 12, 16) Vector(4, 8, 12, 16) Vector(3, 6, 9, 12) Figure 7: Sequential and parallel execution of loop statements. 1 o b j e c t CartesianProduct extends App f 1 o b j e c t CartesianProduct extends App f 2 v a l points = 0 until5 2 v a l points = 0 until5 3 v a l cartessianProduct=for fx<−p o i n t s 3 v a l cartessianProduct = points.flatMap(x 4 y<−p o i n t s g y i e l d f => points .map(y= > ( x , y ) ) ) 5 ( x , y ) 4 p r i n t l n(cartessianProduct) 6 g 5 g 7 p r i n t l n(cartessianProduct) 8 g Output: Output: Vector((0,0), (0,1)...(6,6)) Vector((0,0), (0,1)...(6,6)) Figure 4: Map Syntax Figure 5: For Yield Syntax 3 Listing 5: Parallel Loop Execution 1 o b j e c t ParallelExample extends App f 1 2 v a l integers = 1 until5 import scala.collection.parallel.ParSeq 2 3 v a l timesTable = for (integer1 <− i n t e g e r s ) yield f 3 o b j e c t ParallelExample extends Appf 4 4 f o r f i n t e g e r 2 <− i n t e g e r s v a l integers=ParSeq(1,2,3,4) 5 5 i f (integer2 <= i n t e g e r 1 ) v a l timesTable=for(integer1 <− i n t e g e r s ) 6 g y i e l d f y i e l d f 6 7 i n t e g e r 1 ∗ i n t e g e r 2 f o r(integer2 <− i n t e g e r s ) yield f 7 8 g i n t e g e r 1 ∗ i n t e g e r 2 8 9 g g 9 10 timesTable.