Docsity

Scala String Operations and Functions, Exams of Nursing

Toggle sidebar
bg1
1
Introduction To Scala Programming
Built-in Control Structures : Expressions
Qn. Suppose we have the questions.
1. Write a scala program that will run through a set of 10 marks and print out the marks and their
total sum.
2. Write a scala program that will run through a set of 10 marks and print out the marks and their
corresponding grade according to a given grading criteria.
3. Write a scala program that will scan through the current directory and print out the all the
filesystem
4. Write a scala program that will scan through the current directory and print out the all the files
on only if there are files
As you listen to the question above , we are being directed to what we already know : The use of
control structures.
In Java, C and C++ we have encountered them: decision structures: if, if/else, nested if/else, switch
case structures and Loops: for loop, while loop, and do-while.
Scala provide support for controls structures but has only if , while,do - while , for , try , match , and
function calls control structures.
The reason Scala has so few is that it has provided a rich set of function literals . Instead of
accumulating one higher-level control structure after another in the base syntax, Scala accumulates
function literals in libraries.
NOTE
•One thing you will notice is that almost all of Scala’s control structures result in some value.
So all the above structures should end up resulting to a value.
•This makes it possible for programmers to use these result values to simplify their code, just as
they use return values of functions.
•Without this design feature, the programmer must then create temporary variables just to hold
results that are calculated inside a control structure.
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f

Partial preview of the text

Download Scala String Operations and Functions and more Exams Nursing in PDF only on Docsity!

Introduction To Scala Programming

Built-in Control Structures : Expressions

Qn. Suppose we have the questions.

  1. Write a scala program that will run through a set of 10 marks and print out the marks and their total sum.
  2. Write a scala program that will run through a set of 10 marks and print out the marks and their corresponding grade according to a given grading criteria.
  3. Write a scala program that will scan through the current directory and print out the all the filesystem
  4. Write a scala program that will scan through the current directory and print out the all the files on only if there are files As you listen to the question above , we are being directed to what we already know : The use of control structures. In Java, C and C++ we have encountered them: decision structures: if, if/else, nested if/else, switch case structures and Loops: for loop, while loop, and do-while. Scala provide support for controls structures but has only if , while,do - while , for , try , match , and function calls control structures. The reason Scala has so few is that it has provided a rich set of function literals. Instead of accumulating one higher-level control structure after another in the base syntax, Scala accumulates function literals in libraries. NOTE
  • One thing you will notice is that almost all of Scala’s control structures result in some value. So all the above structures should end up resulting to a value.
  • This makes it possible for programmers to use these result values to simplify their code, just as they use return values of functions.
  • Without this design feature, the programmer must then create temporary variables just to hold results that are calculated inside a control structure.
  • Removing these temporary variables makes the code a little simpler, and it also prevents many bugs.
  • However the while and do-while constructs are called “ loops ,” not expressions , because they don’t result in an interesting value.

Imperative Style Vs Functional Style

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

Example 1: Writing a scala program that will scan through all the integer arguments input at the

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.

Examples of impure functions

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:

  • Read hidden inputs, i.e., they access variables and data not explicitly passed into the function as input parameters
  • Write hidden outputs
  • Mutate the parameters they are given
  • Perform some sort of I/O with the outside world

Writing pure functions

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.

Examples include:

Minimum and Maximum

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

Example

object IfExample2 { def main(args: Array[String]) { var x = 30; if( x < 20 ){ println(“X is not less than 20”); } else { println(x); } } }

If-else-if-else Statement

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.

  • An 'if' can have zero or one else's and it must come after any else if's.
  • An 'if' can have zero to many else if's and they must come before the ending else.
  • Once an else if succeeds, none of he remaining else if's or else's will be tested.

Syntax

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. }

IfExample2a: To illustrate the use of if..else if ..else in Imperative Style

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

If Example2b: To illustrate the use of if..else if ..else in Functional Style

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

IfExample3a: Checking if any argument is passed at the Command line in

Imperative Style

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.

IfExample3a: Checking if any argument is passed at the Command line in

Functional Style.

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.

Example 1: Writing a scala program that will scan through all the integer arguments input at the

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

  • In Scala, as in Java, you must put the boolean expression for a while or an if in parentheses. (In other words, you can’t say in Scala things like if i < 10 as you can in a language such as Ruby. We use if (i < 10) in Scala.)
  • Another similarity to Java is that if a block has only one statement, you can optionally leave off the curly braces,
  • Scala does use semicolons to separate statements as in Java, except that in Scala the semicolons are very often optional. CLASS TASK Modify the scala program above to now print the marks and print the corresponding grade in a tabular format using a grading function that receives marks and return the grade. Example of Iterate using foreach

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.

  • Simple uses that enable common tasks such as iterating through a sequence of integers.
  • More advanced expressions can iterate over multiple collections of different kinds and can filter out elements based on arbitrary conditions, and can produce new collections. Example 1 : Iterating through the args array and printing the values for (arg <- args) println(arg) The parentheses after the “ for ” contain arg <- args. To the right of the <- symbol is the familiar args array and to the left of <- is “ arg ”, which a the name of a val variable, Note It is not a not a var. (Because it is always a val , you just write “ arg ” by itself, not “ val arg ”.) Although arg may seem to be a var , because it will get a new value on each iteration, it really is a val : arg can’t be reassigned inside the body of the for expression. Instead, for each element of the args array, a new arg val will be created and initialized to the element value, and the body of the for will be executed. Example 2: Iterating through a range of integer values Output Iteration 1 Iteration 2 Iteration 3 Iteration 4

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.

Example3 : Lists only those files in the current directory whose names end with “

.scala ”:

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)

Example4 : Nested Filtering

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.

Capitalizing a list of strings

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.”

Using a block of code after yield

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")

  • Imagine that you want to create a new list that has the capitalized names of each person.
  • To do that, you first need to remove the underscore character at the beginning of each name, and then capitalize each name.
  • To remove the underscore from each name, you call drop(1) on each String.
  • After you do that, you call the capitalize method on each string. Here’s how you can use a for-expression to solve this problem: val capNames = for (name <- names) yield { val nameWithoutUnderscore = name.drop(1) val capName = nameWithoutUnderscore.capitalize capName } If you put that code in the REPL, you’ll see this result: capNames: List[String] = List(Adam, David, Frank)

A shorter version of the solution

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.

Handling alternate cases

match expressions are extremely powerful, and we’ll demonstrate a few other things you can do with them.

  1. match expressions let you handle multiple cases in a single case statement. To demonstrate this, imagine that you want to evaluate “boolean equality” like the Perl programming language handles it: a 0 or a blank string evaluates to false, and anything else evaluates to true. This is how you write a method using a match expression that evaluates to true and false in the manner described: def isTrue(a: Any) = a match { case 0 | "" => false // Case 0 or empty case _ => true } Because the input parameter a is defined to be the Any type — which is the root of all Scala classes, like Object in Java — this method works with any data type that’s passed in: scala> isTrue(0) res0: Boolean = false scala> isTrue("") res1: Boolean = false scala> isTrue(1.1F) res2: Boolean = true scala> isTrue(new java.io.File("/etc/passwd")) res3: Boolean = true The key part of this solution is that this one case statement lets both 0 and the empty string evaluate to false: case 0 | "" => false Example2: val evenOrOdd = i match { case 1 | 3 | 5 | 7 | 9 => println("odd") case 2 | 4 | 6 | 8 | 10 => println("even") case _ => println("some other number") }

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") }

2. Using If Expressions In Case Statements

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") }

  1. You can also write the code on the right side of the => on multiple lines if you think is easier to read. Here’s one example: 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") } Here’s a variation of that example that uses curly braces: count match { case 1 => { println("one, a lonely number") } case x if x == 2 || x == 3 => {