0% found this document useful (0 votes)
4 views

Data Abstraction

Uploaded by

jhony
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Data Abstraction

Uploaded by

jhony
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

If it is compiled, strlen (s) is called Here the function Random is impure

each time and strlen needs to iterate over as it is not sure what will be the result when
the whole of ‘s’. If the compiler is smart we call the function.
enough to work out that strlen is a pure
1.4.2 Side-effects (Impure functions)
function and that ‘s’ is not updated in the
loop, then it can remove the redundant As you are aware function has side
extra calls to strlen and make the loop to effects when it has observable interaction
execute only one time. From these what we with the outside world. There are situations
can understand, strlen is a pure function our functions can become impure though
because the function takes one variable as a our goal is to make our functions pure.
parameter, and accesses it to find its length. Just to clarify remember that side effect is
This function reads external memory but not a necessary bad thing.Sometimes they
does not change it, and the value returned are useful (especially outside functional
derives from the external memory accessed. programming paradigm).
Modify variable outside a function
Note One of the most popular side effects is
Evaluation of pure modifying the variable outside of function.
functions does not cause any side
For example
effects to its output
y: = 0
1.4.1 Impure functions let inc (x: int): int:=
y: = y + x
The variables used inside the
return (y)
function may cause side effects though the
functions which are not passed with any
In the above example the value of y
arguments. In such cases the function is
get changed inside the function definition
called impure function. When a function
due to which the result will change each
depends on variables or functions outside
time. The side effect of the inc () function is
of its definition block, you can never be
it is changing the data of the external visible
sure that the function will behave the same
variable ‘y’. As you can see some side effects
every time it’s called. For example the
are quite easy to spot and some of them may
mathematical function random() will give
tricky.
different outputs for the same function call.
From all these examples and
let randomnumber :=
definitions what we can understand about
a := random() the main differences between pure and
if a > 10 then impure functions are
return: a
else
return: 10

5 Function

12th Computer Science_EM Chapter 1.indd 5 23-12-2022 15:42:16


1.4.3 Chameleons of Chromeland
Pure Function Impure Function
problem using function
The return value of The return value Recall the In the Chameleons of
the pure functions of the impure Chromeland problem what you have studied
solely depends functions does in class XI. suppose two types of chameleons
on its arguments not solely depend
are equal in number. Construct an algorithm
passed. Hence, if on its arguments
you call the pure passed. Hence, that arranges meetings between these two
functions with if you call the types so that they change their color to the
the same set of impure functions third type. In the end, all should display the
arguments, you with the same same color.
will always get set of argu­ments,
the same return you might get Let us represent the number of
values. the different chameleons of each type by variables a, b
return values and c, and their initial values by A, B and C,
They do not have For example, respectively. Let a = b be the input property.
any side effects. random(), Date().
The input – output relation is a =
They do not They may modify
b = 0 and c = A + B + C. Let us name the
modify the the arguments
arguments which which are passed algorithm monochromatize. The algorithm
are passed to them to them can be specified as

monochromatize (a, b, c)
Now let’s see the example of a pure
function to determine the greatest common
-- inputs : a = A, b = B, c = C, a = b
divisor (gcd) of two positive integer numbers.
-- outputs : a = b = 0, c = A+B+C
let rec gcd a b :=
if b <> 0 then gcd b (a mod b) In each iterative step, two chameleons
else
of the two types (equal in number) meet and
return a
change their colors to the third one. For
output
example, if A, B, C = 4, 4, 6, then the series
gcd 13 27
1
of meeting will result in
gcd 20536 7826
2 iteration a b c

0 4 4 6
In the above example ‘gcd’ is the name
of the function which recursively called till 1 3 3 8
the variable ‘b’ becomes ‘0’. Remember b
and (a mod b) are two arguments passed to 2 2 2 10
‘a’ and ‘b’ of the gcd function. 3 1 1 12

4 0 0 14

XII Std Computer Science 6

12th Computer Science_EM Chapter 1.indd 6 23-12-2022 15:42:16


In each meeting, a and b each
a, b, c
decreases by 1, and c increases by 2. The
a = b, a = A, b = B, c = C
solution can be expressed as an iterative
algorithm.
True
a>0 a, b, c := a - 1, b - 1, c+2
monochromatize (a, b, c)
-- inputs : a = A, b=B, c=C, a=b False
a = b = 0, c = A + B + C
-- outputs : a = b = 0, c = A+B+C
a, b, c
while a>0
a, b, c := a-1, b-1, c+2
Now let us write this algorithm using
function
The algorithm is depicted in the flowchart
as below let rec monochromatize a b c :=
if a > 0 then
a, b, c := a-1, b-1, c+2
else
monochromatize a b c
return a, b, c

Points to remember:
• Algorithms are expressed using statements of a programming language
• Subroutines are small sections of code that are used to perform a particular task that
can be used repeatedly
• A function is a unit of code that is often defined within a greater code structure
• A function contains a set of code that works on many kinds of inputs and produces a
concrete output
• Definitions are distinct syntactic blocks
• Parameters are the variables in a function definition and arguments are the values
which are passed to a function definition through the function definition.
• When you write the type annotations the parentheses are mandatory in the function
definition
• An interface is a set of action that an object can do
• Interface just defines what an object can do, but won’t actually do it
• Implementation carries out the instructions defined in the interface
• Pure functions are functions which will give exact result when the same arguments
are passed
• The variables used inside the function may cause side effects though the functions
which are not passed with any arguments. In such cases the function is called impure
function

7 Function

12th Computer Science_EM Chapter 1.indd 7 23-12-2022 15:42:16


Hands on Practice

1. Write algorithmic function definition to find the minimum among 3 numbers.


2. Write algorithmic recursive function definition to find the sum of n natural numbers.

Evaluation

Part - I
Choose the best answer (1 Mark)
1. The small sections of code that are used to perform a particular task is called
(A) Subroutines (B) Files (C) Pseudo code (D) Modules
2. Which of the following is a unit of code that is often defined within a greater code
structure?
(A) Subroutines (B) Function (C) Files (D) Modules
3. Which of the following is a distinct syntactic block?
(A) Subroutines (B) Function (C) Definition (D) Modules
4. The variables in a function definition are called as
(A) Subroutines (B) Function (C) Definition (D) Parameters
5. The values which are passed to a function definition are called
(A) Arguments (B) Subroutines (C) Function (D) Definition
6. Which of the following are mandatory to write the type annotations in the function
definition?
(A) { } (B) ( ) (C) [ ] (D) < >
7. Which of the following defines what an object can do?
(A) Operating System (B) Compiler (C) Interface (D) Interpreter
8. Which of the following carries out the instructions defined in the interface?
(A) Operating System (B) Compiler (C) Implementation (D) Interpreter
9. The functions which will give exact result when same arguments are passed are called
(A) Impure functions (B) Partial Functions
(C) Dynamic Functions (D) Pure functions

XII Std Computer Science 8

12th Computer Science_EM Chapter 1.indd 8 23-12-2022 15:42:16


10. The functions which cause side effects to the arguments passed are called
(A) impure function (B) Partial Functions
(C) Dynamic Functions (D) Pure functions
Part - II

Answer the following questions (2 Marks)


1. What is a subroutine?
2. Define Function with respect to Programming language.
3. Write the inference you get from X:=(78).
4. Differentiate interface and implementation.
5. Which of the following is a normal function definition and which is recursive function
definition
i) let sum x y:
return x + y
ii) let disp :
print ‘welcome’
iii) let rec sum num:
if (num!=0) then return num + sum (num-1)
else
return num

Part - III

Answer the following questions (3 Marks)


1. Mention the characteristics of Interface.
2. Why strlen is called pure function?
3. What is the side effect of impure function. Give example.
4. Differentiate pure and impure function.

9 Function

12th Computer Science_EM Chapter 1.indd 9 23-12-2022 15:42:16


Part - IV

Answer the following questions (5Marks)


1. What are called Parameters and write a note on
(i) Parameter without Type (ii) Parameter with Type
2. Identify in the following program
let rec gcd a b :=
if b <> 0 then gcd b (a mod b) else return a

i) Name of the function


ii) Identify the statement which tells it is a recursive function
iii) Name of the argument variable
iv) Statement which invoke the function recursively
v) Statement which terminates the recursion
3. Explain with example Pure and impure functions.
4. Explain with an example interface and implementation.

REFERENCES

1. Data Structures and Algorithms in Python By Michael T.Goodrich, RobertoTamassia and


Michael H. Goldwasser.
2. Data Structure and Algorithmic Thinking in Python By Narasimha Karumanchi
3. https://www.python.org

XII Std Computer Science 10

12th Computer Science_EM Chapter 1.indd 10 23-12-2022 15:42:16


CHAPTER 2
Unit I
DATA ABSTRACTION

2.2 Abstract Data Types


Learning Objectives
Abstract Data type (ADT) is a type
After the completion of this chapter, the for objects whose behavior is defined by a
student will be able to Understand set of values and operations.
• what is Abstract Data structures. The definition of ADT only mentions
• Abstract data type. what operations are to be performed but not
how these operations will be implemented. It
• Difference between concrete and abstract
does not specify how data will be organized
implementation.
in memory and what algorithms will be
• Pairs. used for implementing the operations.
• Data Abstration in Structure. It is called “abstract” because it gives an
implementation independent view. The
2.1 Data Abstraction-
process of providing only the essentials and
Introduction
hiding the details is known as abstraction.
Data abstraction is a powerful You can see that these definitions
concept in computer science that allows do not specify how these ADTs will be
programmers to treat code as objects — for represented and how the operations will be
example, car objects, pencil objects, people carried out. There can be different ways to
objects, etc. Programmers need not to worry implement an ADT, for example, the List
about how code is implemented — they have ADT can be implemented using singly linked
to just know what it does. list or doubly linked list. Similarly, stack
This is especially important when ADT and Queue ADT can be implemented
several people are doing a project. Here using lists.
project refers to the programming .With Data abstraction replicate how we
data abstraction, your group members won’t think about the world. For example, when
have to read through every line of your code you want to drive a car, you don’t need to
to understand. They can just assume that it know how the engine was built or what
does work. kind of material the tires are made of. You
Abstraction provides modularity just have to know how to diver the car. To
(modularity means splitting a program in facilitate data abstraction, you will need to
to many modules). Classes (structures) are create two types of functions: constructors
the representation for “Abstract Data Types”, and selectors.
(ADT)
11

12th Computer Science_EM Chapter 2.indd 11 26-12-2022 17:25:50


2.3 constructors and selectors Notice that you don’t need to know
how these functions were implemented. You
Constructors are functions that are assuming that someone else has defined
build the abstract data type. Selectors are them for us.
functions that retrieve information from
It’s okay if the end user doesn’t know
the data type.
how functions were implemented. However,
For example, say you have an abstract the functions still have to be defined by
data type called city. This city object will someone.
hold the city’s name, and its latitude and
Let us identify the constructors and
longitude. To create a city object, you’d use a
selectors in the above code
function like
As you already know that
city:= makecity (name, lat, lon) Constructors are functions that build the
abstract data type. In the above pseudo code
To extract the information of a city
the function which creates the object of the
object, you would use functions like
city is the constructor.
• getname(city) city:= makecity (name, lat, lon)
• getlat(city)
Here makecity (name, lat, lon) is the
• getlon(city) constructor which creates the object city.
The following pseudo code will (name, lat, lon) value passed as parameter
compute the distance between two city
objects:
make city ( )
distance(city1, city2):
lt1, lg1 := getlat(city1), getlon(city1)
city
lt2, lg2 := getlat(city2), getlon(city2)
return ((lt1 - lt2)**2 + (lg1 - lg2)**2))1/2 lat lon

In the above code read distance(), Fig 1 constructor


getlat() and getlon() as functions and read
lt as latitude and lg longitude. Read := as Selectors are nothing but the
“assigned as” or “becomes” functions that retrieve information from the
data type. Therefore in the above code
lt1, lg1 := getlat(city1), getlon(city1)
• getname(city)
is read as lt1 becomes the value of • getlat(city)
getlat(city1) and lg1 becomes the value of
• getlon(city)
getlon (city1).
are the selectors because these functions
extract the information of the city object
XII Std Computer Science 12

12th Computer Science_EM Chapter 2.indd 12 26-12-2022 17:25:50


city value passed as parameter city value passed as parameter city value passed as parameter

getname ( ) getlat ( ) getlon ( )

Now let us consider one more example to representation is defined as an independent


identify the constructor and selector for a part of the program.
slope.Read - - as comments.
Note
- - constructor A concrete data type is a data type whose
makepoint(x, y): representation is known.
return x, y
- - selector
xcoord(point): Any program consist of two parts.
return point[0] The two parts of a program are, the part
- -selector that operates on abstract data and the part
ycoord(point): that defines a concrete representation, is
return point[1] connected by a small set of functions that
implement abstract data in terms of the
concrete representation. To illustrate this
Note technique, let us consider an example to
Data abstraction is used to define design a set of functions for manipulating
an Abstract Data Type (ADT), which is rational numbers.
a collection of constructors and selectors.
Constructors create an object, bundling Example
together different pieces of information, A rational number is a ratio of
while selectors extract individual pieces integers, and rational numbers constitute
of information from the object. an important sub-class of real numbers.
A rational number such as 8/3 or 19/23 is
typically written as:
2.4 Representation of Abstract
datatype using Rational <numerator>/<denominator>
numbers
where both the <numerator> and
The basic idea of data abstraction is <denominator> are placeholders for integer
to structure programs so that they operate values. Both parts are needed to exactly
on abstract data. That is, our programs characterize the value of the rational number.
should use data in such a way, as to make Actually dividing integers produces a float
as few assumptions about the data as approximation, losing the exact precision of
possible. At the same time, a concrete data integers.

13 Data Abstraction

12th Computer Science_EM Chapter 2.indd 13 26-12-2022 17:25:50


8/3 =2.6666666666666665 component. Let us further assume that the
However, you can create an exact constructor and selectors are also available.
representation for rational numbers by
We are using here a powerful strategy
combining together the numerator and
for designing programs: 'wishful thinking'.
denominator.
We haven't yet said how a rational number
As we know from using functional is represented, or how the constructor and
abstractions, we can start programming selectors should be implemented.
productively before you have an
implementation of some parts of our
Note
program. Let us begin by assuming that
you already have a way of constructing a Wishful Thinking is the formation
rational number from a numerator and a of beliefs and making decisions according
denominator. You also assume that, given to what might be pleasing to imagine
a rational number, you have a way of instead of by appealing to reality.
selecting its numerator and its denominator

Example: An ADT for rational numbers


- - constructor
- - constructs a rational number with numerator x, denominator y
rational(x, y)
- - selector
numer(x) → returns the numerator of rational number x
denom(y) → returns the denominator of rational number y

In the above example, rational () 2.5 Lists,Tuples


is the constructor numer () and denom ()
both are selectors. In this case, selectors To implement the data abstraction,
are declared inside the constructor but not Programming languages like Python
defined. provides a compound structure called Pair
The pseudo code for the which is made up of list or Tuple. The first
representation of the rational number using way to implement pairs is with the List
the above constructor and selector is construct.

x,y:=8,3 2.5.1 List


rational(x,y) List is constructed by placing
numer(x)/denom(y) expressions within square brackets
- - output : 2.6666666666666665 separated by commas. Such an expression
is called a list literal. List can store multiple
values. Each value can be of any type and
can even be another list.

XII Std Computer Science 14

12th Computer Science_EM Chapter 2.indd 14 26-12-2022 17:25:50

You might also like