[go: up one dir, main page]

0% found this document useful (0 votes)
22 views117 pages

FCP Lab Workbook

Uploaded by

abdul rasheed sk
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views117 pages

FCP Lab Workbook

Uploaded by

abdul rasheed sk
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 117

FUNCTIONAL & CONCURRENT

PROGRAMMING
21CS3036 P

STUDENT ID: ACADEMIC YEAR: 2023-24


STUDENT NAME:
Table of Contents

1. Session 01: INTRODUCTION TO SCALA .......................................................................... 01


2. Session 02: FUNCTIONS, LISTS ,STATEMENT SEPARATORAND BLOCKS ............................... 09
3. Session 03: PATTERN MATCHING AND HIGHERORDER FUNCTIONS .................................... 19
4. Session 04: FUNCTIONS & LAMBDAS ,FUNCTIONAL DATA STRUCTURES & INFINITE DATA
STRUCTURES ................................................................................................................. 29
5. Session 05: SCALA :OOP AND FP, CLASSES & OBJECTS ,INHERITANCE MODEL ....................... 39
6. Session 06: TRAITS ,CLASSES WITH POLYMORPHIC TYPES .................................................. 50
7. Session 07: MONOIDS ,FUNCTORS ,MONADS AND TAIL-RECURSIVE FUNCTIONS .................. 62
8. Session 08: ASYNCHRONOUS PROGRAMMING WITH FUTURES AND PROMISES ................... 72
9. Session 09: DATA PARALLEL COLLECTIONS ....................................................................... 79
10. Session 10: CONCURRENCY WITH AKKA .......................................................................... 90
11. Session 11: INTRODUCTION TO ACTOR MODEL ................................................................ 97
12. Session 12: CONCURRENT PROGRAMMING WITH USE CASE ............................................ 107
A.Y. 2023-24 LAB/SKILL CONTINUOUS EVALUATION

S.No Date Experiment Name Pre- In-Lab (25M) Post- Viva Total Faculty
Lab Program/ Data and Analysis & Lab Voce (50M) Signature
(10M) Procedure Results Inference (10M) (5M)
(5M) (10M) (10M)
1. INTRODUCTION TO SCALA -NA-
FUNCTIONS, LISTS ,STATEMENT
2.
SEPARATORAND BLOCKS
PATTERN MATCHING AND HIGHERORDER
3.
FUNCTIONS
FUNCTIONS & LAMBDAS ,FUNCTIONAL
4. DATA STRUCTURES & INFINITE DATA
STRUCTURES
SCALA :OOP AND FP, CLASSES & OBJECTS
5.
,INHERITANCE MODEL
TRAITS ,CLASSES WITH POLYMORPHIC
6.
TYPES
MONOIDS ,FUNCTORS ,MONADS AND
7.
TAIL-RECURSIVE FUNCTIONS
ASYNCHRONOUS PROGRAMMING WITH
8.
FUTURES AND PROMISES
9. DATA PARALLEL COLLECTIONS

10. CONCURRENCY WITH AKKA

11. INTRODUCTION TO ACTOR MODEL


CONCURRENT PROGRAMMING WITH USE
12
CASE
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

Experiment Title: INTRODUCTION TO SCALA

Aim/Objective:

To explore the fundamental concepts of Scala.

Description:

Scala is also a functional language in the sense that every function is a value. Scala provides a
lightweight syntax for defining anonymous functions, it supports higher-order functions, it allows
functions to be nested, and it supports currying. Scala’s case classes and its built-in support for pattern
matching provide the functionality of algebraic types, which are used in many functional languages.
Singleton objects provide a convenient way to group functions that aren’t members of a class.

Pre-Requisites:

• Basics of Scala – data types


• Statements and expressions
• Declarations

Pre-Lab:

Answer the following questions:

1. As we stepped into a new programming language, first of all we need to know how functional
programming is differ from object-oriented programming language .so draft some differences.

A:

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 1 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

2. Below is a program which illustrates the data types. Execute the code and understand the output.

// Scala programto illustrate Data types object Test

def main(args: Array[String])

var a: Boolean = true var a1: Byte = 126

var a2: Float = 2.45673f var a3: Int = 3

var a4: Short = 45

var a5: Double = 2.93846523 var a6: Char = 'A'

if (a == true)

println("boolean: welcome to functional programming!!")

println("byte:" + a1) println("float:" + a2) println("integer:" + a3) println("short:" + a4)


println("double:"

+ a5) println("char:"

+ a6)

A:

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 2 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

3. As Harry is in charge for Scala laboratory. He wants to check the basics for his students and asked
them to print the sum, difference and product of two numbers by taking input from console.

Input format:

The first line contains n(first no) and m(second number)

Constraints:

n < 1000

m < 1000

A:

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 3 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

In-Lab:

1. Grace is new to programming and she wants to learn Scala programming. You need to help her to
initialize variables of all the data types and print the values on console.

Example: An example is shown for single variable. This has to be applied for all the data types var a3:
Int = 3

println("integer:" + a3)

Writing space for the In-Lab: (For Student’s use only)

A:

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 4 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

2. Rohit wants to find the maximum and minimum of salaries that his firm pays which are inputted in
the form an array. Can you help him by writing a Scala program that completes the task for him.

Writing space for the In-Lab:(For Student’s use only)

A:

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 5 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

3. Dora wants to remember week days with the help of numbers. She wants your help to make a
program that prints numbers according to week days.

Example: 0-Sunday 1-Monday 2-Tuesday so on

Writing space for the In-Lab:(For Student’s use only)

A:

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 6 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

Sample VIVA-VOCE Questions (In-Lab):

1. Which Scala library is used for functional programming?

2. What is a ‘Scala set’? What are methods through which operation sets are expressed?

3. How is Scala a programming language with a combination of both functional and object-
oriented programming?

4. Explain the functionality of Yield.

5. What is the advantage of using Scala over other functional programming languages? Define
the features of Immutable Variables?

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 7 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

Post-Lab:

1. Your friend gave you a String "Vanilla Donut 10 2.25", where the literal Vanilla Donut is a particular
donut, the 10 literal is the quantity purchased, and 2.25 is the unit price of each Vanilla Donut. You
further need to cast each token from the input String to their corresponding types, such as, an Int,
Double or String. Parse the corresponding values usingScala.

Writing space for the Post-Lab:(For Student’s use only)

A:

Evaluator Remark (if Any):

Marks Secured: _____out of 50

Signature of the Evaluator with Date

Evaluator MUST ask Viva-voce prior to signing and posting marks for each experiment.

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 8 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

Experiment Title: FUNCTIONS, LISTS, STATEMENT SEPARATOR AND BLOCKS

Aim/Objective:

To explore the Functions, Lists, Statement Separator and Blocks of Scala.

Description:

A Scala method is a part of a class which has a name, a signature, optionally some
annotations, and some bytecode where as a function in Scala is a complete object which can be
assigned to a variable. In other words, a function, which is defined as a member of some object, is
called a method.

Scala Lists are quite similar to arrays which means, all the elements of a list have the same
type but there are two important differences. First, lists are immutable, which means elements of a
list cannot be changed by assignment. Second, lists represent a linked list whereas arrays are flat.

Pre-Requisites:

• Functions, Lists
• Statement separator and blocks

Pre-Lab:

Answer the following questions:

1. A supervisor of a company collecting the age of every employee’s children as he is planning a party
for his son’s birthday. He has got with 50 names as a list. He wants to separate the list with their
respective ages as

5-10

11-15

16-20

21-25

So that he can buy the gifts for them. Help him to sort according to the given groups.

A:

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 9 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

2. Ramesh wants to find the index of particular element but the problem is ,he has a list with him. Help
Ramesh with his problem.

A:

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 10 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

3. Predict the output ofthe following codes

a. val a = (x:Int) => x + 4

val b = (x:Int, y:Int) => x * y

println(a(6))

println(b(3, 5))

b. valfruits=(“apple”,”mango,”orange”,”banana”) fruits (1)

= ”kiwi”

A:

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 11 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

In-Lab:

1. There are N bottles kept in a row and numbered 1 through N from left to right. You are given a
string S with length N, where for each valid i, the i-th character of S is 'A' if the i-th bottle is a Acid or
'B' if this bottle is a Base. Bottles kept next to each other in the row are strong. Jerry is asked to form
neutral potions to save Tom. Each neutral potion must consist of a Acid and a Base. Two bottles can
only form a neutral potion if they are strong. Each bottle can only be part of at most one neutral
potion. What is the maximum number of neutral potions that can be formed?

Input 4

AB

ABBA

AA

ABAAB

Output 1

Writing space for the In-Lab:(For Student’s use only)

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 12 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 13 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

2. Sindhu loves to work with numbers. Given a list of numbers she wants to make all the possible
operations. Help her to make the operations.

a) head()

b) tail()

c) isempty()

d) reverse()

e) fill()

f) concat()

Writing space for the In-Lab:(For Student’s use only)

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 14 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

3. A online bidding company has a list of bidding amounts of a particular product offered by different
customers, as we all know rule of bidding is to select the highest amount offered by customers , so
write a program to find the maximum bid amount

A:

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 15 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

Sample VIVA-VOCE Questions (In-Lab):

1. Define different packages in Scala?

2. Why do we use =(equal) operator in Scala function?

3. What is function composition in Scala?

4. Define Null, Nill, None, and Nothing in Scala?

5. What is the Function parameter with a default value in Scala?

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 16 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

Post-Lab:

1. Given a string s and an integer k, reverse the first k characters for every 2k characters counting from
the start of the string. If there are fewer than k characters left, reverse all of them. If there are less
than 2k but greater than or equal to k characters, then reverse the first k characters and left the other
as original.

Example 1:

Input: s=’’abcdefg” , k=2

Output: “bacdfeg”

Example 2:

Input: s=”abcd” , k=2

Output: “bacd”

A:

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 17 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

2. Jack wants to works on lists. Help him to iterate over a list to print the elements and calculate the
sum and product of all elements of this list using Scala.

A:

Evaluator Remark (if Any):

Marks Secured: _____out of 50

Signature of the Evaluator with Date

Evaluator MUST ask Viva-voce prior to signing and posting marks for each experiment.

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 18 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

Experiment Title: PATTERN MATCHING AND HIGHER ORDER FUNCTIONS

Aim/Objective:

To explore the Pattern Matching and Higher Order Functions.

Description:

Higher order functions take other functions as parameters or return a function as a result. This
is possible because functions are first-class values in Scala. The terminology can get a bit confusing at
this point, and we use the phrase “higher order function” for both methods and functions that take
functions as parameters or that return a function.

In a pure Object Oriented world a good practice is to avoid exposing methods parameterized
with functions that might leak object’s internal state. Leaking internal state might break the invariants
of the object itself thus violating encapsulation.

Pre-Requisites:

• Pattern Matching
• Higher Order Functions

Pre-Lab:

Answer the following questions:

1. Koopis given an assignment by his teacher to write a program that determines the days in a week
using patternmatching. Help Koopin completing his assignment

A:

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 19 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

2. You are given a list of N elements. Reverse the list without using the reverse function. The input
and output portions will be handled automatically. You need to write a function with the
recommended method signature.

Input Format:

Each element, X , of the list is displayed on a separate line Output Format:

The output is the reverse of the input list. Sample Input:

19

22

28

26

17

18

28

Sample Output:

28

18

17

26

28

22

19

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 20 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 21 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

In-Lab:

1.Given two integers, and , a recursive technique to find their GCD is the Euclidean Algorithm. The
algorithm states that, for computing the GCD of two positive integers x and y , if and are equal, GCD(x,
y)=x. Otherwise GCD(x, y)= GCD(x-y, y) if x>y . There are a few optimizations that can be made to the
above logic to arrive at a more efficient implementation.

Ramu is trying to calculate the GCD of two numbers and needs to verify his answer so, Implement
GCD, the function that computes the greatest common divisor of two numbers Using Recursion.

Input : 14 21 Output:7

Writing space for the In-Lab:(For Student’s use only)

2. John and Vicky are two neighbors in a colony and they don't about each other. So John want to
know the age of Vicky and they both like programming and decided to play a small game. So John want
to guess the age of Vicky and Vicky will tell each time whether his age is equal or greater or lesser than
the age told by John. You should write a menu driven program such that they have 2 options 1.Enter
the age of Vicky 2.Exit

Note: Use Pattern matching i.e. casesfor finding the age is equal , greater or lesser told by John.

You find the age of Vicky inthe below example testcases andimplement the code using pattern
matching.

Example:

Game starts

1. Enter the age of Vicky : 20

Output : The age you entered is lesser than the actual age

2. Enter the age of Vicky : 27

Output : The age you entered is greater than the actual age 3.Enter the age of Vicky : 25

Output : Hurry !! Super John , You have found my age exactly . My age is 25 . 4.Exit Game ends

Writing space for the In-Lab:(For Student’s use only)

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 22 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 23 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

Sample VIVA-VOCE Questions (In-Lab):

1. There is a task that you need to write a program for day in a week ,through which concept
you complete this task in Scala ?

2. How pattern guards are useful?

3. How a case class can use pattern matching?

4. What are methods through which operation can be performed on sets?

5. What are the Case classes in Scala?

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 24 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

Post-Lab:

1. Ram is a B tech 1st year student his teacher gave a list of decimal numbers and ask him to
convert them to hexadecimal numbers help Ram in converting the list of numbers to
hexadecimalnumbers using Scala.

Sample input:

[26,30]

Sample output:

"1a"

"001e"

Writing space for the Post-Lab:(For Student’s use only)

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 25 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 26 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

2. Help a Home teaching center in taking the input of 3 students with details name and age and then

printing the details of students as “name: xyz, Age: 19 is registered” if the age of the person is less

than 25 and greater than 19 and print “You are not eligible” if the age is greater than 25 using the

concept pattern matching. Create a caseclass student with parameters name and age.

Writing space for the Post-Lab:(For Student’s use only)

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 27 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

Evaluator Remark (if Any):

Marks Secured: _____out of 50

Signature of the Evaluator with Date

Evaluator MUST ask Viva-voce prior to signing and posting marks for each experiment.

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 28 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

Experiment Title: FUNCTIONS & LAMBDAS ,FUNCTIONAL DATA STRUCTURES & INFINITE DATA
STRUCTURES

Aim/Objective:

To explore the functions & lambdas, functional data structures & infinite data structures in
scala.

Description:

Scala lambda functions are anonymous functions. They reduce the line of code and make the
function more readable and convenient to define. We can also reuse them. We can use this lambda
function to iterate our collection data structure and performed any kind of operation on them. Also
lambdas functions are very light weighted in syntax hence make the code more under stable.

Pre-Requisites:

• Functions and Lambdas, Functional Data Structures: Immutable Lists and Maps Lazy
• Passing, Lazy Val, Streams and Other Infinite Data Structures.

Pre-Lab:

Answer the following questions:

1. Black widow and Hawkeye went to Vormir to get the soul stone. While traveling they must pass a
few tests to reach the stone. The stone keeper stops them and asked to solve a question – “you have
to write the following function using lambda function

def func():

li=[5,8,10,20,50,100]

sum=0 for i in li:

sum=sum + i print(sum)

to get the stone so, can you?”. Help them to solve the test and get the soul stone.

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 29 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

2. Watson was given homework to write a program that prints the list of numbers that are divisible
by 25 between the range 25 to 200 using lambdas and functions.

Output: List(25, 50, 75, 100, 125, 150, 175)

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 30 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

3. At Hogwarts Albus Dumbledore announces that the school will host the Triwizard Tournament, in
which three magical schools compete across challenges. The Goblet of Fire selects the champions to
take the part in the competition. The Goblet unexpectedly selected Harry as a champion. For the first
task, each champion must retrieve a golden egg guarded by a dragon. Harry succeeds in retrieving his
egg in which contains a test to solve to go to the second challenge. The test is "Givenx, y are user
inputs, you have to output x^y (exponent) using lambdas". Help harry in solving his test and proceed
to the second challenge.

4. The second task involves the champions diving underwater to rescue someone valuable to them.
Harry rescues Ronald and Gabrielle. He got the secondgolden egg which contains another test to go
to the final challenge. The test is " He is given a list of integers, multiply the elements of the list by the
user given value using lazy evaluation. List->(1,2,3,4,5)". Help harry in passing the test and proceed to
the final challenge.

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 31 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

In-Lab:

1. Winsome pets are a pet adoptionagency. Winsomepet’s agency wants to have a recordof pets and
the people who have adoptedthe pets from their agency. They consider dogs, cats, parrots, squirrels,
rabbits, monkeys to give a sweet home to these animals. Help the Winsome pet agency to collect the
details of the customer, having attributes like name, which pet they wish to adopt and their contact
number. (Use Scala oops to solve this problem). Since the winsome pet’s agency has a problem with
their log files, help them to resolve the issue. (Use lazy variablesto help the agency.)

Writing space for the In-Lab:(For Student’s use only)

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 32 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

2. Harry is learning the concepts of functional programming in Scala and understanding more in-depth
concepts like parameter passing, functions, and immutable lists.

a) Declare an immutable list with 4 names and using call by name mechanism define a function and
call that function to add the two names to the list, print the head, element at index 1, and last value
of the list.

b) Let us play with numbers. Make a simple calculator using a Scala map. Declare functions for
addition, subtraction, division, andmultiplication. Take the input of the two numbers from the user
and what operation he intends to perform. Map the respective functionto a value andprint the result
of the operation by accessing the respective function.

(Ex: Map(“addition” -> add(x, y))

Writing space for the In-Lab:(For Student’s use only)

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 33 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 34 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

Sample VIVA-VOCE Questions (In-Lab):

1. What is the difference between seq and list in scala?

2. What is a Scala map? Are maps immutable or mutable?

3. What is lazy evaluation and lazy Val?

4. Why Scala Prefers Immutability?

5. What Is Range in Scala? How To Create a Rangein Scala?

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 35 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

Post-Lab:

1. Aslan is teaching Lucy andedmund on the topic of immutable maps. So he gave them a basic
question. The question is Create an empty immutable

map(implemented by List Map) and do the following operations :

add few elements, print a certainvalue from the Map, delete a few elements and print the map. Help
Lucy and edmund to solve this question

Writing space for the Post-Lab:(For Student’s use only)

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 36 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

2. In the world of wizardry Harry, Hermione and Ronald are best friends. One day Hermione challenged
Ronald to answer the followingquestions. Help Ronald to win the challenge as Harry is busy learning
new magic spells.
a) Hermione gave Ronald a list of numbers they are 144,100,81…etc.

She challenged him to print the square root of the list of numbers using lambda functions in Scala

output:

List(12.0, 10.0, 9.0)

b) Hermione gave Ronald again a list of numbers they are 10,45,63 etc. She challenged himto print

the surface area assuming each number as a side of a cube output:

List(600,12150,23814)

Writing space for the Post-Lab:(For Student’s use only)

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 37 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

Evaluator Remark (if Any):

Marks Secured: _____out of 50

Signature of the Evaluator with Date

Evaluator MUST ask Viva-voce prior to signing and posting marks for each experiment.

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 38 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

Experiment Title: SCALA: OOP AND FP, CLASSES & OBJECTS ,INHERITANCE MODEL

Aim/Objective:

To explore the OOP and FP, classes & objects, inheritance model in scala.

Description:

Inheritance is an important pillar of OOP(Object Oriented Programming). It is the mechanism


in Scala by which one class is allowed to inherit the features(fields and methods) of another class.

Class

In Scala, a class declaration contains the class keyword, followed by an identifier(name) of the
class. But there are some optional attributes which can be used with class declaration according to
the application requirement. In general, class declarations can include these components, in order:

Keyword class: A class keyword is used to declare the type class.

Class name: The name should begin with a initial letter (capitalized by convention).

Superclass(if any):The name of the class’s parent (superclass), if any, preceded by the keyword
extends. A class can only extend (subclass) one parent.

Traits(if any): A comma-separated list of traits implemented by the class, if any, preceded by
the keyword extends. A class can implement more than one trait.

Body: The class body is surrounded by { } (curly braces).

Object

It is a basic unit of Object Oriented Programming and represents the real-life entities. A typical
Scala program creates many objects, which as you know, interact by invoking methods. An object
consists of :

State: It is represented by attributes of an object. It also reflects the properties of an object.

Behavior: It is represented by methods of an object. It also reflects the response of an object


with other objects.

Identity: It gives a unique name to an object and enables one object to interact with other
objects.

Pre-Requisites:

• Functions in Scala and Object-Oriented Programming,


• Scala: OOL and FP, classes and objects, inheritance model

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 39 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

Pre-Lab:

Answer the following questions:

1. A student is studying the basic concepts of FP. He wants to understand every concept to the core.
All he knows is that an Armstrong number is a number that is equal to the sum of cubes of its digits.
But he is new to the functional programming language Scala. Help him in writing a function to print all
Armstrong numbers between given intervals using functions in Scala.

Input :

Input lower limit: 1 Input upper limit:1000 Output:

Armstrong numbers between 1 to 1000 are: 1, 153, 370, 371, 407.

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 40 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

2. John is preparing for a coding interview. There is a question asked on functional programming in
the question bank. The question is to implement a class Student and create an object and access the
members to display the element name, id, address, and age. Help him write the program in Scala.

3. Tom riddle observed that many of the natural things follow the Fibonacci sequence. He recalled
the series and he know that F0 = 0, F1 = 1 and that Fi = Fi−1+Fi−2. So he decided to implement it in
Scala using tail-recursive functions.

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 41 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

4. Bill wants to greet his employees everyday. Now create a class Employee with property name and
greet() method to print the greeting message. And now create an object Hello and create an instance
to above class and call the method defined above to print the greeting message.

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 42 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

In-Lab:

1. Captainparrot likes to ask the pirates some questions. She ordered to solve one such question that
is to use a case class to define a shopping cart item in scala. Each shopping cart item shouldhave the
following properties, namely, a name, a price, and a quantity bought. Create three shopping cart items
for the following items: 10 vanilla ice cream at $2.99 each 3 chocolate biscuits at $3.99 every 5
cupcakes at $4.99 each

Use an appropriate data structure to store the above-mentionedshopping cart items. Thereafter,
define and use a method that will print out all items from a given shopping cart. Output: 10 vanilla ice
cream at $2.99 each 3 chocolate biscuits at $3.99 each 5 cupcakes at $4.99 each

Define also another method that is given a shopping cart basket that will only output vanilla ice cream
products. A generic message, such as, "Foundanother item", will be the output for all other items.
Output: Found another item. Found another item. Found a cupcake item.

Writing space for the In-Lab:(For Student’s use only)

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 43 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

2. Susan Pevensie is working on a project. The question is to define a base abstract class to model a
Vehicle type that has a public property of type String using scala. This particular Vehicle base class
will be extended by two subtypes, namely, a Car, and a Bike case class, and will wire accordingly the
make property of type String from the Vehicle base class. Next, create a singleton object named
Vehicle Report that will define a print Vehicles method that will have as input a List of Vehicle types,
and any of its subtypes or subclasses. The printVehicles() method will simply iterate through each of
the Vehicle type and output its corresponding make property. Note that the printVehicles() method
will have no return type defined as such. You can use the following vehicle samples to model your
data points:
a car whose make is: bmw 3 series a car whose make is: vw golf

a bike whose make is: bmw g 310 r bike a bike

whose make is: firestorm bike

Use the List data structure from Scala's collection type and store the above- mentioned vehicles.
And, finally, call the Vehicle Reports printVehicles() method by passing through your collection of
vehicles as defined above.

Output:

bmw 3 series vw golf

bmw g 310 r bike firestorm bike

Writing space for the In-Lab:(For Student’s use only)

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 44 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 45 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

Sample VIVA-VOCE Questions (In-Lab):

1. Explain the usage of inheritance.


A:

2. What is Scala Anonymous Function?


A:

3. Explain implicit classes with syntax


A:

4. Can a companion object in Scala access the private members of its companion class in Scala?
A:

5. How is Scala is both an Object oriented and Functional Programming Language?


A:

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 46 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

Post-Lab:

1. Three students Bill, Tommy, Cindy are teaching Jonny some concepts. They prepared a question
"Use an appropriate data structure to present the following key and value pairs of children and their
ages: Bill is 9 years old, Jonny is 8 years old, Tommy is 11 years old, and Cindy is 13 years old". Sort out
the corresponding child to age in reverse alphabet order.
Writing space for the Post-Lab:(For Student’s use only)

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 47 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

2. Bill went to a car race and a bike race. Now he is confused about the difference between the speeds
of cars and bikes in races. So that creates a Parent class called Vehicle with val mph of integer data
type and declare race() method for printing the race type. Now create Child classes Car and Bike that
inherit the Vehicle class override the mph and race() methods. Now, inside the main method, create
a Car object and a Bike object and then access their property mph and method race.
Writing space for the Post-Lab:(For Student’s use only)

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 48 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

3. At Hogwarts still, the Triwizard tournament is going on. As Harry won the first and second challenges
still he needs to win the final challenge to reach the Triwizard cup and final golden egg. For the final
task, the champions must reach the Triwizard Cup and a golden egg located in the hedge maze. The
hedge maze is very tricky and dangerous. Finally, Harry reached the Triwizard Cup and the last golden
egg. To return from the maze, He has to solve the final task in the egg. The task is- "Implement a class
atom and create an object and access the members to display the element name, electron count, and
symbol." .Helpharry in solving the final challenge to get the Triwizard cup and win the Triwizard
tournament.
Writing space for the Post-Lab:(For Student’s use only)

Evaluator Remark (if Any):

Marks Secured: _____out of 50

Signature of the Evaluator with Date

Evaluator MUST ask Viva-voce prior to signing and posting marks for each experiment.

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 49 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

Experiment Title: TRAITS ,CLASSES WITH POLYMORPHIC TYPES

Aim/Objective:

To explore the traits, classes with polymorphic types in scala.

Description:

In Scala, Traits are a fundamental concept of object-oriented programming that provides a


mechanism to reuse code. Traits are similar to interfaces in Java, but with the added advantage of
providing concrete implementations of methods as well as the ability to include fields. Traits can be
mixed into classes to provide additional functionality without using inheritance. This makes them a
powerful tool for modular code design and reuse.

Pre-Requisites:

• Traits, Classes with Polymorphic Types

Pre-Lab:

Answer the following questions:

1. Try to execute the given following stack program and understand how we used the parametric
polymorphism concept in this program. Code:

object GenericPolyPlayground {

trait GenericStack[T] { var elms: List[T] = Nil

def push(x: T) { elms = x :: elms } def peak(): T = elms.head

def pop(): T =

val h = elms.head elms = elms.tail h

val intStack = new GenericPolyPlayground.GenericStack[Int] {} intStack.push(1)

println(s"with generic polymorphism it will just pop 1, so boring:

${intStack.pop()}") A:

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 50 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 51 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

2. What does the following code print?

trait Cool { var speak = "I am groovy"}object JoeCamel extends Coolprintln(JoeCamel.speak)

3. Write a program which contains Polymorphism in Scala. It shouldcontain 3 functions included in it.
The 3 functions should give their outputs as sum, subtractions and multiplication.

Sample outputs:

First Execution:50 Second Execution:120 Third Execution:300

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 52 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

In-Lab:

1. Ram is a manager at a Software company and he wants his Employees to build a scientific calculator
and he call all members of the deveoper team and assigned some tasks to each member of the team.
Ram wants to reduce mistakes/confusion in tasks given to employees so he gave trait interface to each
employee so the emloyees know what are the tasks they have to do by extending that trait interface.
But one of the employee names Jay was not able to do his task beacause he is going for a vacation
with his family and you are the friend of Jay and your task is to help Jay by doing is work.
The work is to implement a scala program use the Trait interface named 'ToDo' given by manager and
do implementation logic by extending that trait in another class named 'MyTask', Override all the
abstrat fields which are in trait interface, and in main method take user input and take user option for
calculation pass that input values to the class MyTask which have implementation of abstract methods
to to performuser requiredcalculation.

trait given by manager is: trait ToDo{


def add: Int
def subtract: Int
def multiplication: Int def mod: Int
def division: Int
}

Writing space for the In-Lab:(For Student’s use only)

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 53 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 54 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

2. Raj was studying in Harvard University. His teacher ask raj to find the area of Square and Circle and
raj is good in programming and wants to do this by polymorphism. So mam asked raj to take a base
class "Shape" which has a two functions named "getArea" where one function takes "side" of Int
datatype and other take radius of Double Datatype and write the respective formula for each function
and return the result. We use these functions named "getArea" to find areas. So we need write a
derived class "Area" where this class takes two parameters as side and radius of Int and Double
datatypes respectively. You need to call the function getArea and give parameters for each one.
As the functions return the value you need to print them in derived class. Note: Create two variables
Square and Circle in derived class to call the getArea methods.

Writing space for the In-Lab:(For Student’s use only)

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 55 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 56 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

Sample VIVA-VOCE Questions (In-Lab):

1. When can you use traits?


A:

2. What is a Trait? When is it used?


A:

3. What Is Diamond Problem? How Scala Solves Diamond Problem?


A:

4. What are the two principal forms of Polymorphism?


A:

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 57 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

Post-Lab:

1. Harsha uses social media so much that he uploads every moment i.e. pictures into it. He uses a app
called "Social" in which when we upload a picture it does some common operations on each image
which is uploaded into it which might include i) compressing the image ii) scaling that in various sizes
iii) extracting a snapshot of the image of the video. But Harsha want a additional feature in it that is
he want to cut a frame out of that image when he uploads.
(Hint: Here we are doing abstract override such a combination is only possible in traits. Let us see
example code of Imagecompressortrait so that you can define a trait for the new feature (that is cut
a frame from the image)):

trait ImageCompressor extends ImageProcessor { abstract override def process(name: String) = {


println("Compressing Image"); super.process(name)
}
}
Here ImageProcessor class is the abstract class.
So help him to add the additional feature into it using traits in Scala

Writing space for the Post-Lab:(For Student’s use only)

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 58 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 59 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

2. Chanduis studying about classes with polymorphic types he need to know about usage of many
functions with the same name. The task is in the first function we need to print a single integer value
and secondtask we need to add 2 integers and in 3rd task we need product of 3 integers.
input format:
120
50,70
10,5,6

output format:
First Execution:120 Second Execution:120 Third Execution:300

Writing space for the Post-Lab:(For Student’s use only)

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 60 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

Evaluator Remark (if Any):

Marks Secured: _____out of 50

Signature of the Evaluator with Date

Evaluator MUST ask Viva-voce prior to signing and posting marks for each experiment.

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 61 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

Experiment Title: MONOIDS, FUNCTORS ,MONADS AND TAIL-RECURSIVE FUNCTIONS

Aim/Objective:

To explore the MONOIDS, FUNCTORS, MONADS AND TAIL-RECURSIVE FUNCTIONS.

Description:

Monoid extends the Semigroup type class, adding an empty method to semigroup's combine.
The empty method must return a value that when combined with any other instance of that type
returns the other instance, i.e.

(combine(x, empty) == combine(empty, x) == x)

Pre-Requisites:

• Monoids
• Functors
• Monads
• Tail-recursive functions

Pre-Lab:

Answer the following questions:

1. You are asked to find a way to calculate the factorial of a number in which the recursion that takes
place is optimized by the compiler. Using that way try to find the factorial of any number given by a
user.
A:

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 62 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

2. Haneefa has been given a task by his teacher to reverse a list using tail recursion help him write the
codein Scala?
A:

3. Ram wants to implement a simple tail recursion program to calculate GCD of given two numbers
but he failed to implement the code So you have to implement the Tail recursion code to find GCD for
given two numbers to help him.
Hint: Use the following method definition inyour code @tailrec def gcd(a: Int, b: Int):Int = ……
A:

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 63 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

In-Lab:

1. We have a contest on Twitter . You are givensome users and there followers. The user having most
followers wins!. Try finding who is the winner using Scala monoids? You have to
return winners name.

Name Username Followers

harmeetsingh singh_harmeet13 132


knoldus knolspeak 575
vikas vhazrati 387
dzone dzone 10670
scala scala_lang 20421

Output:

Winner – scala

Writing space for the In-Lab:(For Student’s use only)

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 64 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 65 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

2. Ram wants to sort out his rice bags in the order of their weights and wants to perform using the
language Scala. Can you perform this operation for Ram using Scala tail-recursionconcept?

Writing space for the In-Lab:(For Student’s use only)

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 66 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

3. Yosuko was a student in Japan and he was not that much confident incoding. He came across a
problem that is he need to sort the list of numbers using tailrec concept in scala but Yosuko don't
know how to do it and you are the friend of him. Write the scala code to sort the list of numbers
manually using Scala Tail Recursion concept and help your friend in understanding your code.

Input:

[5,8,10,3,1,6]

output:

[1,3,6,5,8,10]

Writing space for the In-Lab:(For Student’s use only)

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 67 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

Sample VIVA-VOCE Questions (In-Lab):

1. Can you convert this Recursion function into a loop? Problem A(x) {

if x<0 return 0;

return something(x)+ A(x-1)

A:

2. What is a good example of Recursion (other than generating a Fibonacci sequence)?

A:

3. Why is tail recursion better than normal recursion?

A:

4. Why are Functors, Monads, Monoids used in Functional Programming?

A:

5. What is recursion tail in Scala?

A:

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 68 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

Post-Lab:

1. Ravi was a student in Oxford University. He joined after 10 days of college reopened. So On the first
day his mam gave homework on the topic of tail recursion. The question is you will be give an array
,you need to find the least difference of factorials of elements in the array. As it was new to him he
asked you. Help him to implement the factorial function using tail recursion concept.
Input:
[6,2,5,8,3]
Output:
4
Writing space for the Post-Lab:(For Student’s use only)

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 69 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

2. Ram wants to conduct a contest and he wants the list of members who are coming from different
regions sorted. He also wantsthe total score of all participants combined. Suggest him a way of
performing this operation.Hint: Perform insertion sort using tail-recursion and thenuse monadic
methods to find the totalscore.
Writing space for the Post-Lab:(For Student’s use only)

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 70 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

Evaluator Remark (if Any):

Marks Secured: _____out of 50

Signature of the Evaluator with Date

Evaluator MUST ask Viva-voce prior to signing and posting marks for each experiment.

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 71 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

Experiment Title: ASYNCHRONOUS PROGRAMMING WITH FUTURES AND PROMISES

Aim/Objective:

To explore the asynchronous programming with futures and promises.

Description:

A Future is a placeholder object for a value that may not yet exist. Generally, the value of the
Future is supplied concurrently and can subsequently be used. Composing concurrent tasks in this way
tends to result in faster, asynchronous, non-blocking parallel code.

By default, futures and promises are non-blocking, making use of callbacks instead of typical
blocking operations. To simplify the use of callbacks both syntactically and conceptually, Scala
provides combinators such as flatMap, foreach, and filter used to compose futures in a non-blocking
way.

Pre-Requisites:

• Asynchronous Programming with Futures


• Asynchronous programming with promises

Pre-Lab:

Answer the following questions:

1. A learner asked a trainer towriteafuture companion object.He also asked him


tousescala.concurrent.Futuremethod. So what is the answer given by the trainer?
A:

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 72 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

2. After learning about future, Karthik wants to get started with promise. Help him define apply
method(single assignment variable) on the Promise companion object, so that the method creates
new promise instance.

A:

3. Karthik is trying to get a webpage's contents when given a url string with the locationof the
webpage.

For this purpose, he defined the method as follows :

def getWebpage(url: String): String

Using the concept of 'future', changethe returnvalue of the getWebpage method to some special value
that can be returned immediately.

A:

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 73 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

In-Lab:

1. Karthik wants to explore promise further. Help him create two promises, p and q, that can hold
string values, install a foreach callback on the future associated with the p promise and wait for 1
second. The callback is not invoked until the p promise is completed by calling the success method,
fail the q promise in the same way and install a failed.foreach callback.

Writing space for the In-Lab:(For Student’s use only)

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 74 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

2. Create a FixedThreadPool to execute our asynchronous code.


a. create a Promise
b. create a Runnable and wrap the block to be run asynchronously in the run method
c. close the promise and complete the promise using the result of the run
d. execute the Runnable in the somePool threadpool.
e. return the promise.future from which the caller can read the value.

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 75 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 76 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

Sample VIVA-VOCE Questions (In-Lab):

1. How is the async/await paradigmdifferent from Promises?


A:

2. What is a “Future” object in Scala? Is it an immutable object?


A:

3. Differentiate between a Javafuture and a Scala future.


A:

4. How does asynchronous programming helpyoueliminate blocking?


A:

5. What are the two abstractions in Scala that are specifically tailored for this task— futures
and promises
A:

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 77 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

Post-Lab:

1. A task is given to the students regarding promises ,solve the task along with them
Task : Create a Promise
a. complete the Promise by setting a successful value
b. then return the read side of the Promise – the Future back to the caller by using the
promise.future

Evaluator Remark (if Any):

Marks Secured: _____out of 50

Signature of the Evaluator with Date

Evaluator MUST ask Viva-voce prior to signing and posting marks for each experiment.

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 78 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

Experiment Title: DATA PARALLEL COLLECTIONS

Aim/Objective:

To explore the data parallel collections.

Description:

Scala's parallel collections are a way to provide users with simple and safe tools to perform
parallel programming. They come at the expense of reduced generality; however, for a vast number
of parallel applications, they will be a simple and sufficient solution. Parallel collections work by
providing parallel versions of various Scala collection classes.

Pre-Requisites:

• Data parallel collections

Pre-Lab:

Answer the following questions:

1. Elsa and anna are classmates. Their teacher asked them to work on parallel connections. For
Understanding more using a parallel filter to select the last names that come alphabetically after the
letter “I”. Use map method

A:

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 79 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

2. Show how the following two parallel collections are implemented by executing an example
program for both of:

a) Side – effecting Operations

b) Non – associative Operations

A:

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 80 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

3. Tarun and Varun are good friends. Varun is absent for his FCP class due to his illness. He asks Tarun
to explain him the concepts that were dealt in that class. So help Tarun to make Varun understand the
Parallel collection classes by giving an example for each of:

• ParArray

• ParVector

• mutable.ParHashMap

• mutable.ParHashSet

• immutable.ParHashMap

• immutable.ParHashSet

• ParRange

• ParTrieMap

A:

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 81 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

In-Lab:

1. Your are the CR in your class and your class teacher assigned a work to the you , the work is to divide
the class students into two batches such that the first batch contains students whose starting letter is
from A-I and second batch contains students whose starting letter is from J-Z. Complete the work
using parallel filter Sample input:

"Smith","Jones","Frankenstein","Bach","Jackson","Rodin" Sample output:

Batch 1: Frankenstein, Bach

Batch 2: Smith, Jones, Jackson, Rodin

Writing space for the In-Lab:(For Student’s use only)

A:

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 82 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 83 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

2. Fiona just learned the concept of parallel collections in Scala. Her friend Phoebe said that she
didn't understandand asked her for help. Phoebe asked Fiona to just explain a simple example of the
cube of numbers but Fiona is busy with some other work. Help phoebe by explaining an example
program of printing cube of 10 numbers using parallel collections in Scala. The output can be in any
order Output:

64

125

1000

27

512

729

343

216

Writing space for the In-Lab:(For Student’s use only)

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 84 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 85 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

Sample VIVA-VOCE Questions (In-Lab):

1. Define the process of Creating a Parallel Collection


A:

2. Can we go back to original collection from Scalaparallel collection


A:

3. Why do we use parallel collection classes in Scala


A:

4. Explainstreams in Scala.
A:

5. What is a BitSet?
A:

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 86 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

Post-Lab:

1. Oliver Twist from a workhouse in town MudFog needs to understand data-parallel collection classes
to impress his master Mr. Bumble to provide him more gruel. His master ordered him to separate boys
of the workhouse withthe letter O from the list Peter, Tom, Oliver, George, Ruthandtransform the
collectionof all strings to uppercase usingScala

A:

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 87 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

2. Naresh is an administrator in KL University. He has a list of students who opted for JAVA, Python
and C++ courses in the college. He has to design a logic using parallel collections in order to display
the names of students who opted for:

i) only java ii)only python iii)only c++

iv)both java and python v)both java and c++ vi)both c++ and python vii)all the three languages

input format:

first line is list of students in java, followed by Python followed by C++

EXAMPLE to understand input format:

‘A’,’B’,’C’,’X’,’P’ //list of students in Java

‘P’,’Q’,’R,’A’,’X’ //list of students in python

‘B’,’Q’,’X’,’Y’,’Z’,’A’ //list of students in c++ You need to print 7 lines in the output as explained
above

Writing space for the Post-Lab:(For Student’s use only)

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 88 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

Evaluator Remark (if Any):

Marks Secured: _____out of 50

Signature of the Evaluator with Date

Evaluator MUST ask Viva-voce prior to signing and posting marks for each experiment.

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 89 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

Experiment Title: CONCURRENCY WITH AKKA

Aim/Objective:

To explore the concurrency with akka.

Description:

Akka is an event-driven middleware toolkit for building high performance and reliable
distributed applications in Java and Scala. Akka decouples business logic from low-level mechanisms
such as threads, locks and non-blocking IO. Our Scala or Java program logic lives in lightweight actor
objects which send, receive and process messages.

Pre-Requisites:

NIL

Pre-Lab:

Answer the following questions:

1. Rajeshhave got to know about Akka. He further wants to know the approach of akka toolkit. Please
tell him it’s approach.

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 90 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

2. Rajesh now knew the approach of the Akka toolkit and it’s actor-system. Now he wants to
implement it. Help him getting-started with the system with actor class template.

3.By seeing that Rajesh’s progress in concurrency topics ,his friend Rahul also wants to know the
concept of Akka Actor in Scala. Help him to write a simple program. Create a actor class Hello
anddefine receive method, create case class Msg to print the message. Now create an object Main
and

define ActorSystem, actorOf() methodto create instance of Hello class and send message to newly
create actor using tell operator.

A:

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 91 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

In-Lab:

1. Raju wants his student Ravi to calculate the addition, subtraction, multiplication and division. Help
Ravi to do all operations in Scala using concurrency with akka actors. Construct the case classes Add,
Subtract, Multiply, Divide with parameters a and b type integers and create the actor classes Addition,
Subraction, Multiplication, Division, define receive method and usecase classes to print the results.
Create a actor class Operation, define receive method and use the above created case classes, use
actorOf() method to create the instance of Addition, Subtraction, Division classes .Now create the
object Calculator, create Actor System and use actorOf() method to create instance of Operation and
define the integers using tell operator.

Writing space for the In-Lab:(For Student’s use only)

A:

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 92 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

2. After Trying out the hello world application, he wants to learn and try Props. Help him with an
example in props.

Writing space for the In-Lab:(For Student’s use only)

A:

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 93 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

Sample VIVA-VOCE Questions (In-Lab):

1. How does Akka handle concurrency?


A:

2. What is use of Akka Props?


A:

3. What is Akka and how to implement it?


A:

4. What is Akka ActorSystem ? Explain the components in Akka ActorSystem.


A:

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 94 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

Post-Lab:

1. Ramya wants to wishher friend Akhila for celebrating her birthday as she enters 18 years at
12:00am.Help her to wish her friend with message "Happy Birthday Akhila" and "You entered
18,Akhila and our friendship too". Construct a case classes greet parameter name, celebrate
parameters name and age and an actor birthday and define recieve methoduse the above definedcase
classes and print the appropriate messages. Nowcreateobject Party, create ActorSystemand use
actorOf() method to create instance of Birthday and send messages to newly created actor with tell
operator and shutdownthe actor system
Writing space for the Post-Lab:(For Student’s use only)
A:

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 95 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

2. After building some simple concurrent applications using Akka, Rajeshnow wants to build a
concurrent application that finds numberof words in a text of single line. Writing space for the Post-
Lab:(For Student’s use only)
A:

Evaluator Remark (if Any):

Marks Secured: _____out of 50

Signature of the Evaluator with Date

Evaluator MUST ask Viva-voce prior to signing and posting marks for each experiment.

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 96 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

Experiment Title: Introduction to Actor Model

Aim/Objective:

To explore the Actor Model in scala.

Description:

• an actor encapsulates its state and part of the application logic


• actors interact only through asynchronous messages and never through direct method calls
• each actor has a unique address and a mailbox in which other actors can deliver messages
• the actor will process all the messages in the mailbox in sequential order (the default
implementation of the mailbox being a FIFO queue)
• the actor system is organized in a tree-like hierarchy
• an actor can create other actors, can send messages to any other actor and stop itself or any
actor is has created

Pre-Requisites:

• Introduction to the Actor Model


• The Actor Model in Practice

Pre-Lab:

Answer the following questions:

1. Henry just learned the concept of the Actor model. Dennis didn't understand the concept and
asked Henry for help. Dennis asked to explain an example. Henry got an idea to explain a program of
sending and receiving messages i.e., if he sends a message in a string, it should be printed as Message:
message. If he sends a number it shouldprint the cube of the number as Cube of the number: cube.
Help Dennis to understand the concept by writing a program as henry is busy with his homework.
Input:
"Hello world" 10
Output:
Message: Hello world Cube of the number:1000
A:

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 97 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 98 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

2. They said that ,typical implementationof an actor consists of pattern matching .But many of the
students doesn’t have a correct idea regarding this. Now your task is to make students to understand
about that statement which can identify the message type and react accordingly.
A:

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 99 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

In-Lab:

1. Nolan is working in a supermarket part-time. He is studying for the semester exam in his free time.
His lecturer is considerate and he prepareda question for him to solve so that he can understand the
concepts better. Consider a supermarket with 2 actors cashier and customers of any number. Assume
that the supermarket contains 3 items newspapers, chocolates, and cheese. Take multiple customers
with different product lists from the above-given items. Write 2 classes for cashier and customer. Let
the case classes total, chocolate, cheese, and price have some appropriate arguments and 2 objects
for newspaper and thanks message. The customer class shouldhave 3 arguments product list,
customer name, andcashier. The cashier class has the argument price. Help Nolan to write the code.

Writing space for the In-Lab:(For Student’s use only)

A:

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 100 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 101 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

2. While learning a lot regarding Actor andrelated topics ,mike readthat it has some life cycle methods
and wanted to have a program on Akka actor life cycle methods so that he can get the complete idea
.Provide the required implementation for mike.

Writing space for the In-Lab:(For Student’s use only)

A:

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 102 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

Sample VIVA-VOCE Questions (In-Lab):

1. Why should Akka messages be immutable?


A:

2. Why do we use actor model?


A:

3. Do actors onlycommunicatethroughmessages?
A:

4. What is anActorRef?
A:

5. What operations do Actor in ActorModel perform?


A:

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 103 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

Post-Lab:

1. John lost a game while playing on his pc. Suddenly he remembered he is late for school and has to
complete an assignment about actor replying to messages. He sent a message “I lost” as a sender. He
wants a reply to the previous message as “Better luck next time”. Help him with his assignment before
he runs late to his college.
Output:
Message received : I lost Replying
Message received : Better luck next time
Writing space for the Post-Lab:(For Student’s use only)
A:

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 104 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

2. Mr Dumbledore is preparing questions for the owls test for his students. He is currently teaching
forwarding messages in akka. Before that he wants to check how to forward message “FCP course”
from one actor to another. Provide a solution tohim
Writing space for the Post-Lab:(For Student’s use only)
A:

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 105 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

Evaluator Remark (if Any):

Marks Secured: _____out of 50

Signature of the Evaluator with Date

Evaluator MUST ask Viva-voce prior to signing and posting marks for each experiment.

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 106 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

Experiment Title: Concurrent Programming with Use Case

Aim/Objective:

To explore the Concurrent Programming with Use Case.

Description:

Concurrency is when more than one task can start and complete in overlapping time periods.
It doesn’t matter whether they’re running at the same instant. You can write concurrent programs on
a single CPU (single execution core) machine where only one task can execute at a given point of time.
Typically multiple tasks are executed in a time-slice manner, where a scheduler (such as the JVM) will
guarantee each process a regular “slice” of operating time.

Pre-Requisites:

• Concurrent Programming with Reactive Extensions


• Use Case – A Parallel Web Crawler

Pre-Lab:

Answer the following questions:

1. Helix has a topic Reactive Extensions which he missed in the class and he thinks that it is
hard to him. So he wants to learn from the basic program to complex programs in this topic. He
wants to start from "Hello world" program and move to next program. Help him to print "Hello
world" on the console using the concept Reactive programming.

A:

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 107 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

2. After learning about parallel web crawler in the class, Raman wants to draw the architecture of it.
Draw the architecture of parallel webcrawler which Raman would draw.

A:

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 108 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

In-Lab:

Writing space for the In-Lab:(For Student’s use only)


A:

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 109 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 110 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

Sample VIVA-VOCE Questions (In-Lab):

1. What Are ReactiveExtensions?


A:

2. How does concurrent programming workwith Reactive Extensions?


A:

3. What are some most used web crawlers?


A:

4. What is the difference between Akka Kill vs Stop vs Poison Pill?


A:

5. Briefly explainthe components of an Actor


A:

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 111 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

Post-Lab:

1. Ravi and you are going to build a web application which you want to add comparison feature but
you want to compare one product across the products in the given website so for that you need a
webcrawling. But both of you don't know how to implement web crawling. So to understand Web
Crawling implement a simple Scala program.
You can create your specific crawler by subclassing Crawler class for a
crawler who's effects (crawling web) are captured by fs2.Task and that gives us data only in form of
String. Let's make a crawler that follows every https link and gives us url's of websites.
Writing space for the Post-Lab:(For Student’s use only)

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 112 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

2. Pawan wants to write a scala program for Putting the read and write protocol togetherfor an actor
,since Pawan was a beginner helphimto write the code

Writing space for the Post-Lab:(For Student’s use only)

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 113 of 116
Experiment # <TO BE FILLED BY STUDENT> Student ID <TO BE FILLED BY STUDENT>
Date <TO BE FILLED BY STUDENT> Student Name <TO BE FILLED BY STUDENT>

Evaluator Remark (if Any):

Marks Secured: _____out of 50

Signature of the Evaluator with Date

Evaluator MUST ask Viva-voce prior to signing and posting marks for each experiment.

Course Title FUNCTIONAL & CONCURRENT PROGRAMMING ACADEMIC YEAR: 2023-24


Course Code(s) 21CS3036P Page 114 of 116

You might also like