FCP Lab Workbook
FCP Lab Workbook
PROGRAMMING
21CS3036 P
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
Aim/Objective:
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:
Pre-Lab:
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:
2. Below is a program which illustrates the data types. Execute the code and understand the output.
if (a == true)
+ a5) println("char:"
+ a6)
A:
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:
Constraints:
n < 1000
m < 1000
A:
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)
A:
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.
A:
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.
A:
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?
5. What is the advantage of using Scala over other functional programming languages? Define
the features of Immutable Variables?
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.
A:
Evaluator MUST ask Viva-voce prior to signing and posting marks for each experiment.
Aim/Objective:
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:
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:
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:
println(a(6))
println(b(3, 5))
= ”kiwi”
A:
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
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()
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:
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:
Output: “bacdfeg”
Example 2:
Output: “bacd”
A:
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 MUST ask Viva-voce prior to signing and posting marks for each experiment.
Aim/Objective:
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:
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:
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:
19
22
28
26
17
18
28
Sample Output:
28
18
17
26
28
22
19
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
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
Output : The age you entered is lesser than the actual age
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
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 ?
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"
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.
Evaluator MUST ask Viva-voce prior to signing and posting marks for each experiment.
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:
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=sum + i print(sum)
to get the stone so, can you?”. Help them to solve the test and get the soul stone.
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.
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.
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.)
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.
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
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
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:
b) Hermione gave Ronald again a list of numbers they are 10,45,63 etc. She challenged himto print
List(600,12150,23814)
Evaluator MUST ask Viva-voce prior to signing and posting marks for each experiment.
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:
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:
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.
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 :
Identity: It gives a unique name to an object and enables one object to interact with other
objects.
Pre-Requisites:
Pre-Lab:
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 :
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.
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.
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.
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
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:
4. Can a companion object in Scala access the private members of its companion class in Scala?
A:
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)
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)
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 MUST ask Viva-voce prior to signing and posting marks for each experiment.
Aim/Objective:
Description:
Pre-Requisites:
Pre-Lab:
1. Try to execute the given following stack program and understand how we used the parametric
polymorphism concept in this program. Code:
object GenericPolyPlayground {
def pop(): T =
${intStack.pop()}") A:
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:
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.
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.
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)):
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
Evaluator MUST ask Viva-voce prior to signing and posting marks for each experiment.
Aim/Objective:
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.
Pre-Requisites:
• Monoids
• Functors
• Monads
• Tail-recursive functions
Pre-Lab:
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:
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:
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.
Output:
Winner – scala
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?
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]
1. Can you convert this Recursion function into a loop? Problem A(x) {
if x<0 return 0;
A:
A:
A:
A:
A:
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)
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)
Evaluator MUST ask Viva-voce prior to signing and posting marks for each experiment.
Aim/Objective:
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:
Pre-Lab:
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.
Using the concept of 'future', changethe returnvalue of the getWebpage method to some special value
that can be returned immediately.
A:
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.
5. What are the two abstractions in Scala that are specifically tailored for this task— futures
and promises
A:
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 MUST ask Viva-voce prior to signing and posting marks for each experiment.
Aim/Objective:
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:
Pre-Lab:
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:
2. Show how the following two parallel collections are implemented by executing an example
program for both of:
A:
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:
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:
A:
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
4. Explainstreams in Scala.
A:
5. What is a BitSet?
A:
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:
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:
iv)both java and python v)both java and c++ vi)both c++ and python vii)all the three languages
input format:
‘B’,’Q’,’X’,’Y’,’Z’,’A’ //list of students in c++ You need to print 7 lines in the output as explained
above
Evaluator MUST ask Viva-voce prior to signing and posting marks for each experiment.
Aim/Objective:
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:
1. Rajeshhave got to know about Akka. He further wants to know the approach of akka toolkit. Please
tell him it’s approach.
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:
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.
A:
2. After Trying out the hello world application, he wants to learn and try Props. Help him with an
example in props.
A:
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:
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 MUST ask Viva-voce prior to signing and posting marks for each experiment.
Aim/Objective:
Description:
Pre-Requisites:
Pre-Lab:
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:
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:
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.
A:
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.
A:
3. Do actors onlycommunicatethroughmessages?
A:
4. What is anActorRef?
A:
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:
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:
Evaluator MUST ask Viva-voce prior to signing and posting marks for each experiment.
Aim/Objective:
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:
Pre-Lab:
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:
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:
In-Lab:
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)
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
Evaluator MUST ask Viva-voce prior to signing and posting marks for each experiment.