







































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!








































Qn. Suppose we have the questions.
Before we dive into the built in scala control structures let us briefly discuss the functional style of programming supported by scala When we write an iteration code using the while ,the do-while and the for loops as in java , then we are programming in an imperative style. In the imperative style, which is the style you normally use with languages like Java, C++, and C, we write one imperative command at a time, iterate with loops, and often mutate state shared between different functions. Let us consider the very usual while loop case below-mentioned
command line and print them out and their sums. object LoopExample1 { def main(args: Array[String]) ={ var i = 0 var sum = 0 while (i < args.length) { println(args(i))//prints out the ith command line argument sum =sum + Integer.parseInt(args(i)) // You understand this? i += 1 //increments i by one. } println(sum) }//End of main }//End of class The sum variable in the above code is changed ( mutated ) in side the while loop. With Scala you can program imperatively but it also enable you program in a functional style. You are advised in this course that you become as comfortable with the functional style as you are with imperative style. Functional programming is a style of programming that emphasizes writing applications using only pure functions and immutable values. This means functional programming have strongly focuses on a desire to see their code as math : to see the combination of their functions as a series of algebraic equations. In that regard, you could say that functional programmers like to think of themselves as mathematicians.
An application isn’t very useful if it can’t read or write to the outside world, so people make this recommendation: Write the core of your application using pure functions, and then write an impure “wrapper” around that core to interact with the outside world. Consider the case of putting a layer of impure icing on top of a pure cake. There are ways to make impure interactions with the outside world feel a little more pure.
Conversely, the following functions are impure because they violate the definition. The foreach method on collections classes is impure because it’s only used for its side effects, such as printing to STDOUT. A great hint that foreach is impure is that it’s method signature declares that it returns the type Unit. Because it returns nothing, logically the only reason you ever call it is to achieve some side effect. Similarly, any method that returns Unit is going to be an impure function. Date and time related methods like getDayOfWeek, getHour, and getMinute are all impure because their output depends on something other than their input parameters. Their results rely on some form of hidden I/O , hidden inputs. In general, impure functions do one or more of these things:
Writing pure functions in Scala is one of the simpler parts about functional programming: You just write pure functions using Scala’s method syntax. Here’s a pure function that doubles the input value it’s given: def double(i: Int): Int = i * 2 Here’s a pure function that calculates the sum of a list of integers (List[Int]): def sum(list: List[Int]): Int = list match {
case Nil => 0 case head :: tail => head + sum(tail) } Even though we haven’t covered recursion, if you can understand that code, you’ll see that it meets my definition of a pure function. In Built Scala Functions Scala has a rich set of math functions in package scala.math The package object scala.math contains methods for performing basic numeric operations such as elementary exponential, logarithmic, root and trigonometric functions. All methods forward to java.lang.Math unless otherwise noted.
Find the min or max of two numbers. Note: scala.collection.IterableOnceOps has min and max methods which determine the min or max of a collection. def max(x: Int, y: Int): Int def max(x: Long, y: Long): Long def max(x: Float, y: Float): Float def max(x: Double, y: Double): Double def min(x: Int, y: Int): Int def min(x: Long, y: Long): Long def min(x: Float, y: Float): Float def min(x: Double, y: Double): Double For a complete reference to scala math functions visist- https://dotty.epfl.ch/api/scala/math.html
object IfExample2 { def main(args: Array[String]) { var x = 30; if( x < 20 ){ println(“X is not less than 20”); } else { println(x); } } }
An 'if' statement can be followed by an optional ' else if...else ' statement, which is very useful to test various conditions using single if...else if statement. When using if , else if , else statements there are few points to keep in mind.
The following is the syntax of an ‘if...else if...else’ is as follows − if(Boolean_expression 1){ //Executes when the Boolean expression 1 is true } else if(Boolean_expression 2){ //Executes when the Boolean expression 2 is true } else if(Boolean_expression 3){ //Executes when the Boolean expression 3 is true } else { //Executes when the none of the above condition is true. }
object IfExample2 { def main(args: Array[String]) ={ var x =Math.ceil(Math.random()*100); if( x >= 70 ){ println(x+": A"); } else if( x >= 60 ){ println(x+": B");
} else if( x >= 50 ){ println(x+": C"); } else if( x >= 40 ){ println(x+": D"); } else{ println(x+": F"); } }//End of main }//End of class
object IfExample3 { def main(args: Array[String]) ={ val x =Math.ceil(Math.random()*100); val grd=if( x >= 70 ) x+": A" else if( x >= 60 ) x+": B" else if( x >= 50 ) x+": C" else if( x >= 40 ) x+": D" else x+": F" println(grd) }//End of main }//End of class
var filename = "default.txt" if (!args.isEmpty) filename = args(0) This code declares a variable, filename , and initializes it to a default value. It then uses an if expression to check whether any arguments were supplied to the program at the command line. If so, it changes the variable to hold the value specified in the argument list. If no arguments were supplied, it leaves the variable set to the default value.
Remember that Scala’s if is an expression that results in a value. This example shows how you can accomplish the same effect as the previous example, but without using any vars: val filename = if (!args.isEmpty) args(0) else "default.txt"
interpreted to a java byte code.). In java we use : i. Integer.valueOf() to Convert a String to an Integer This method returns the string as an Integer object. which is not the desired result. ii. Integer.parseInt() to Convert a String to an Integer This method returns the string as a primitive type int which is what we want.
command line and print them out and their sums. object LoopExample1 { def main(args: Array[String]) ={ var i = 0 var sum = 0 while (i < args.length) { println(args(i))//prints out the ith command line argument sum =sum + Integer.parseInt(args(i)) // You understand this? i += 1 //increments i by one. } println(sum) }//End of main }//End of class Explanation The args.length gives the length of the args array. The while block contains three statements, each indented two spaces , the recommended indentation style for Scala. Note that Java’s ++i and i++ don’t work in Scala. To increment in Scala, you need to say either i = i + 1 or i += 1. Note
One of the main characteristics of a functional language is that functions are first class constructs. For example, another (far more concise) way to print each command line argument is: args.foreach(arg => println(arg)) In this code, you call the foreach method on args , and pass in a function. In this case, you’re passing in a function literal that takes one parameter named arg. The body of the function is println(arg). In the previous example, the Scala interpreter infers the type of arg to be String, since String is the element type of the array on which you’re calling foreach. If you want to be more explicit, you can mention the type name, but you must wrap the argument portion in parentheses (which is the normal form of the syntax anyway): args.foreach((arg: String) => println(arg)) What about the ever popular for loop You may have been accustomed to using the for loops in imperative languages such as Java or C. Scala does not make use of the for loop but provide a for expression which is designed for all purposes to be used only a functional style. Scala’s for expression is a Swiss army knife of iteration. It lets you combine a few simple ingredients in different ways to express a wide variety of iterations.
In each iteration, a new val named file is initialized with an element value. The compiler infers the type of file to be File , because filesHere is an Array[File]. For each iteration, the body of the for expression, println(file) , will be executed. Because File ’s toString method yields the name of the file or directory, the names of all the files and directories in the current directory will be printed. Example 3 Filtering Through a Collection Sometimes you want to filter through a collection down to some subset. You can do this with a for expression by adding a filter : A is an if clause inside the for ’s parentheses.
val filesHere = (new java.io.File(".")).listFiles for (file <- filesHere if file.getName.endsWith(".scala")) println(file) You could alternatively accomplish the same goal with this code: for (file <- filesHere) if (file.getName.endsWith(".scala")) println(file)
To use more filters depending on the application, you can add more if clauses. Example: The code below prints only files and not directories. It does so by adding a filter that checks the file ’s isFile method. ( Check java File I/o Methods) Note that ff you add more than one filter on a generator , the filter’s if clauses must be separated by semicolons. for ( file <- filesHere if file.isFile; if file.getName.endsWith(".scala") ) println(file)
Nested iteration The for Expression We are used to nested loops in imperative programming and there are cases that require us to nest loops.. With the for expression we can use multiple nested generators (that is multiple <- clauses ) to implement nested loops. Example The for expression shown below has two nested loops. The outer loop iterates through filesHere , and the inner loop iterates through fileLines(file) for any file that ends with .scala. def fileLines(file: java.io.File) =scala.io.Source.fromFile(file).getLines.toList def grep(pattern: String) = for ( file <- filesHere if file.getName.endsWith(".scala"); line <- fileLines(file) if line.trim.matches(pattern) ) println(file +": "+ line.trim) grep(".gcd.") You can also use curly braces instead of parentheses to surround the generators and filters. One advantage to using curly braces is that you can leave off some of the semicolons that are needed when you use parentheses. Example2.: Command Line Arguments Type the following into a new file named Example2.scala : object Example2 { def main(args: Array[String]) ={ println("Hello, " + args(0)+ "!") var i = 0 // Printing argument values while (i < args.length) { println(args(i)) i += 1 } } } then run: $ scala Example2.scala James John Wandera Here "James John and Wandera" are passed as a command line argument, which is accessed in the script as args(i).
val nums = Seq(1,2,3) You can create a new list of integers where all of the values are doubled, like this: val doubledNums = for (n <- nums) yield n * 2 That expression can be read as, “For every number n in the list of numbers nums, double each value, and then assign all of the new values to the variable doubledNums.” scala> val doubledNums = for (n <- nums) yield n * 2 doubledNums: Seq[Int] = List(2, 4, 6) As the REPL output shows, the new list doubledNums contains these values: List(2,4,6) The result of the for-expression is that it creates a new variable named doubledNums whose values were created by doubling each value in the original list, nums.
You can use the same approach with a list of strings. For example, given this list of lowercase strings: val names = List("adam", "david", "frank") You can create a list of capitalized strings with this for-expression: val ucNames = for (name <- names) yield name.capitalize The REPL shows how this works: scala> val ucNames = for (name <- names) yield name.capitalize ucNames: List[String] = List(Adam, David, Frank) Success! Each name in the new variable ucNames is capitalized. The yield keyword Using yield after for is the “secret key” that instruct the compiler to a new collection from the existing collection that is being iterated over in the for-expression.”
The code after the yield expression can be as long as necessary to solve the current problem. For example, given a list of strings like this: val names = List("_adam", "_david", "_frank")
The above example you can also be writen in a more concise approach, which is the Scala style of doing things: val capNames = for (name <- names) yield name.drop(1).capitalize You can also put curly braces around the algorithm, if you prefer: val capNames = for (name <- names) yield { name.drop(1).capitalize } Scala match Expressions Scala provide for a match expression. In the most simple way you can use a match expression like a Java switch statement: // i is an integer i match { case 1 => println("January") case 2 => println("February") case 3 => println("March") case 4 => println("April") case 5 => println("May") case 6 => println("June") case 7 => println("July") case 8 => println("August") case 9 => println("September") case 10 => println("October") case 11 => println("November") case 12 => println("December")
println(result) Using a match expression as the body of a method is also a common use.
match expressions are extremely powerful, and we’ll demonstrate a few other things you can do with them.
Example3 that shows how to handle multiple strings in multiple case statements: cmd match { case "start" | "go" => println("starting") case "stop" | "quit" | "exit" => println("stopping") case _ => println("doing nothing") }
Another great thing about match expressions is that you can use if expressions in case statements for powerful pattern matching. In this example the second and third case statements both use if expressions to match ranges of numbers: count match { case 1 => println("one, a lonely number") case x if x == 2 || x == 3 => println("two's company, three's a crowd") case x if x > 3 => println("4+, that's a party") case _ => println("i'm guessing your number is zero or less") } Scala doesn’t require you to use parentheses in the if expressions, however you can use them if you think that makes them more readable: count match { case 1 => println("one, a lonely number") case x if (x == 2 || x == 3) => println("two's company, three's a crowd") case x if (x > 3) => println("4+, that's a party") case _ => println("i'm guessing your number is zero or less") }