You are on page 1of 35

Brief Overview of Ada :-

Ada is intended to support the construction of large programs by team of programmers.


An Ada program is ordinarily designed as a collection of larger software components
called packages ,each representing an abstract data type or a set of data objects shared
among subprograms.

Ada provides a broad range of built-in data types , including


integers,reals,enumerations,booleans,arrays,records,character

An Ada program consists of single procedure that serves as a main program.


An Ada program may involve a set of separate tasks that are to execute concurrently.
The Ada virtual computer utilizes a central stack for each separate task.

Ada is a structured, statically typed, imperative, wide-spectrum, and object-oriented


high-level computer programming language, extended from Pascal and other languages.

Ada is widely used in critical systems, where any anomaly might lead to very serious
consequences, e.g., accidental death or injury. Examples of systems where Ada is used
include avionics, weapon systems (including thermonuclear weapons), and spacecraft.
Avionics is a combination of the words "aviation" and "electronics". It comprises
electronic systems for use on aircraft, artificial satellites and spacecraft.
--Ada example to sum an array
package ArrayCalc is
type Mydata is private;
function sum return integer;
procedure setval(arg : in integer);
private
size : constant :=99;
type myarray is array(1..size) of integer;
type Mydata is record
val : myarray ;
sz : integer:=0;
end record;
v : Mydata;
end;
package body ArrayCalc is
function sum return integer is
temp : integer ;
---Body of the function sum
begin
temp:=0;
for i in 1..vz loop
temp := temp + v.val(i);
end loop
v. sz :=0
return temp;
end sum;
procedure setval (arg : in integer) is
begin
v . sz : =v . sz + 1 ;
v . val( v . sz) :=arg ;
end setval ;
end;
with Text_IO ; use Text_IO;
with ArrayCalc ; use ArrayCalc;
procedure main is
k , m : integer
begin -- of main
get ( k );
while k > 0 loop
for j in 1 . . k loop
get ( m ) ; put( m , 3);
setval (m);
end loop;
new_line ; put(“SUM = “);
put(ArratCalc .sum , 4 );
new_line ; get(k);
end loop;
end;
Primitive Data Types in Ada
The primitive data types which are defined in the package Standard of Ada are as
follows:-
integer
float
character
Boolean
string
Variables and Constants in Ada :-
Any data object may be defined as either a constant or variable.
MaxSize : constant integer :=500;
CurrentSize : integer : =0;
WeekDays : constant array(1..5) of string (1..3):=(“MON” , “TUE” , “WED”, “THU”,
“FRI”)
Lower bound of any vector data type , Vect is Vect’First
Upper bound of any vector data type, Vect is Vect’Last.
Numerical data types in Ada:-
type DayOfYear is range 1..366; --An integer value from 1 to 366
MyBirthday : DayOfYear:=219; --MyBirthday initialized to August 7
type Result is digits 7 ; --foat type of 7 digits
Answer:Result; --7 digit float variable

Enumerations:-
type class is (Fresh , Soph , Junior , Senior);
The run time representation of enumeration values uses the position number for each
literal value , starting with 0 for the first value listed , 1 for the second value , and so on

The same literal name may be used in several enumerations. Such a literal name is said
to be overloaded.
type BreadStatus is (Stale , Fresh);
overloads the literal name Fresh
To specify explicitly which meaning of Fresh is intended at a point in the program
where both the types class and BreadStatus are visible ,the programmer may qualify the
literal name with the name of the base type
(eg., class(Fresh) or BreadStatus(Fresh)).
Structured Data Types in Ada:-
Vectors and arrays : -
An array data object may be declared with any number of
dimensions with arbitrary subscript ranges and any type of component .For example
Table : array (1..10 , 1..20) of float;
creates a 10 x 20 matrix of real numbers

Subscripting is used to select components( e.g., Table(2,3)).


For example , the array type definition might be
type Matrix is array (integer range< >,integer range< >) of float ;
where < > , is called a box , indicates a subscript range to be filled in when variable of
type Matrix data object .For example
Table : Matrix(1..10 , 1..20);

The subscript range need not be a integer range:-


NewList : array(1 . . N) of ListItem;
where N is a variable with a computed value
Slice is defined as a contiguous sub vector of the original vector.
Example:- NewList(2..4)

Initialization:-
PowerOfTwo : array(1..6) of integer : = ( 2 , 4 , 8 , 16 , 32 , 64) ;
Character strings:-
type string is array (positive range< >) of character
Ex:- MyString : string(1..30) ;

File data types:-


Files and input-output operations in Ada are defined as abstract data types using several
predefined packages.

User-Defined Types
A default value may be given for any component of a record , as in :-
type Birthday is
record
Month : string(1..3) : = “Jan” ;
Day : integer range 1..31 : =17;
Year : integer range 1950.. 2050 :=1969 ;
end record;
If you want to put some initial values in place of default values then proceed as :-
YourDay : Birthday : = (“MAR” , 13 , 1968);
YourDay : Birthday : = (Month=>”MAR” , Day=>13,Year=>1968);
type Wage Type is (hourly ,salaried) ;
type EmployeeRec (PayType : WageType) is
record
Name : string(1..30)
Age : integer range 15..100 ;
case PayType is
when Hourly =>
Hours : float ;
HourlyRate : float ;
when Salaried =>
MonthlyRate : float ;
end record ;
President : EmployeeRec(salaried);
Chauffeur : EmployeeRec(hourly);
Subtypes:-
A subtype of that base type consists of a subset of those data objects that meet a
particular constraint.
subtype Executive is EmployeeRec(Salaried);
Derived types :-
A derived type is similar to a sub type , but a derived type is a new type different from
base type
type DerivedTypeName is new basetypename;
type Meters is new integer ;
type Litres is new integer ;

A derived type is allowed to use all the operations defined on the base type (or subtype).
However , because the derived type is a distinct type from the base type ,operations cannot be
applied to mixtures of operands of the base type and derived type.

Sequence Control:-
if Boolean expression then
-statement sequence
elsif Boolean expression then
-statement sequence
elsif Boolean expression then
-statement sequence
…..
else
- statement sequence
end if ;
CASE statements :-
The general form of the case statement is
case expression is
when choice|…|choice => statement sequence ;
when choice|…|choice => statement sequence ;
when others =>statement sequence
end case

case GradeLevel is
when Fresh=>statements ;
when Soph | Junior =>statements;
when Senior => statements ;
end case ;

If no action is required for some choice , the statement part may be the keyword null.
Loop statement:-
The basic iteration statement has the form
loop
- sequence of statements
end loop
The loop iterates endlessly until terminated by an explicit exit , goto , or return
statement or an exception.
Controlled iteration may be created via while or for forms of the loop statement.
The while has the syntax
while boolean expression
for clause:-
It has two forms
for variable name in discrete_range
for variable name in reverse discrete_range

The declaration of variable name is done implicitly by the Ada compiler.


Exit statement:-
The exit statement has the form
exit when Boolean_expression ;
or simply exit.
When an exit statement is executed , it transfers control to the end of innermost
enclosing loop.
Alternatively , loops may be labeled and the exit statement may give the label of the
enclosing loop to be exited .For example
exit OuterLoop when A( i , j) = 0 ;

Pragma:- A pragma is a statement used to convey information to the compiler .It is not
considered to be part of the language
pragma INLINE (subprograms)
pragma OPTIMIZE(TIME or SPACE) –The subprogram within which this declaration
occurs should be compiled so as to minimize its execution TIME or storage SPACE
requirements.
Tasks:-
A task is a subprogram that may be executed concurrently with other tasks
task taskname is
-entry declarations
end ;
task body taskname is is
-sequence of statements
begin
-sequence of statements
exception
-exception hanlers
end ;
Packages :-
The Ada package provides for encapulation
A package specification has two parts : a specification (containing a visible part and a
private part) and a body.
The general form of a package definition is :-
package packagename is
- declarations of visible data objects
private
- complete definitions of private data objects
package body packagename is
- definitions of data objects and subprograms declared
in the specification part above
begin
- statement to initialize the package when first instantiated
exception
- exception handlers
end ;
Perl Overview:-
Perl language is well suited for the handling of regular expressions.
Perl is an interpreted language designed for efficient text –processing applications.
The language included pattern matching , file handling , and scalar data.
Newer versions of the language include object oriented classes.
The growth of the WWW has led to Perl being a language well suited for Web
interaction to process information that is entered on a web page.

Variables in Perl are either integers or strings and begin with the symbol $.
It also has arrays and associative arrays
A simple Perl program consists of a series of print statements.

Perl includes the usual sequence of control structures such as for , while and if
conditional.
Perl can be used for image creation and manipulation, networking via telnet,
ssh or ftp (and others), graphical user interface creation, robotics,
bio-informatics, VLSI electronics and to create mail filters to minimize spam.
Bioinformatics is the application of statistics and computer science to the field
of molecular biology.
Perl example to sum an array:-
1 #!/usr/bin/perl
2 @inputdata = split(/ / ,<STDIN>);
3 $count = 0 ;
4 foreach $nextone (@inputdata)
5 { print “$nextone “ ;
$count = $count + $nextone ; };
7 print “Sum = “;
8 print “$count\n”;
Line 1:Inform the operating system that this shell script will be interpreted by the perl
program.
Line 2: Read the input data and separate at each blank into array inputdata.
Line 4-6: Access each input value in inputdata and add it to count.
For each loop iteration , nextone is assigned the next element in the array.
Print out answers as well as final endline character.
The split function is used like this:-
$info = "Caine:Michael:Actor:14, Leafy Drive"; @personal = split(/:/, $info); which
has the same overall effect as @personal = ("Caine", "Michael", "Actor", "14, Leafy
Drive");
1 %lisp
2 >; Store values as a list of characters
3 >(define (SumNext V)
4 (cond ( (null V) (progn (print “Sum = “) 0 ) )
5 (T (+ ((SumNext (cdr V) ) (car V) ) ) ) )
6 SUMNEXT
7 >; Create vector of input values
8 (defun GetInput(f c)
9 (cond ( (eq c 0) nil )
10 (T (cons (read f) (GetInput f (-c 1) ) ) ) ) )
11 GETINPUT
12 >defun DoIt( )
13 (progn
14 (setq infile (open “lisp.data”) )
15 (setq array (GetInput infile (read infile) ) )
16 (print array)
17 (print (SumNext array ) ) ) )
18 DOIT
19 >(DoIt)
Conditionals.
The conditional is the major structure for providing alternative execution sequencing in
a LISP program. The syntax is
(cond alternative 1
alternative 2
---------------
alternative n
(T default_expression) )
where each alternative i is (predicate i expression i)
cond executes by evaluating each predicate i , in turn , and evaluating expression i of
the first one returning true(T). If all predicates are false ,default_expression is
evaluated.
(car L ) returns a pointer to the first list element.
(cdr L ) returns a pointer to the list with the first element deleted.

By using cons any list may be constructed element by element


(cons A (cons B (cons C nil ) constructs a list of the three elements referenced by A,B
and C
If L = (A B C) is a list.
(car L) is A.
(car (cdr L) is B.
(car (cdr (cdr L) ) ) is C.
The defun function is used to create new functions.
(defun function_name (arguments) expression)

Alternatively, the syntax


(define (function_name arguments) expression)
Structural Patterns - Decorator Pattern
• The decorator pattern helps to add behavior or responsibilities to an object.
This is also called “Wrapper”. Suppose we have some 6 objects and 2 of them
need a special behavior, we can do this with the help of a decorator.
Java Design Patterns suggest that Decorators should be abstract classes and
the concrete implementation should be derived from them.
• The decorator pattern can be use wherever there is a need to add some
functionality to the object or group of objects.
public abstract class Beverage
{ String description = "Unknown Bevrage";
public String getDescription()
{ return description; }
public abstract double cost();
}
public abstract class SpecialDecorator extends Beverage
{ public abstract String getDescription(); }
class MasalaTea extends Beverage
{ public MasalaTea( )
{ description="Masala Tea"; }
public double cost()
{ return 10.00 ; }
}
class GingerTea extends Beverage
{ public GingerTea()
{ description = "Ginger Tea"; }
public double cost()
{ return 5.00; }}
}
public class Elaichi extends SpecialDecorator
{
Beverage beverage ;
public Elaichi(Beverage beverage)
{
this.beverage=beverage;
}
public String getDescription()
{
return beverage.getDescription() + "Elaichi";
}
public double cost( )
{
return 5.00+beverage.cost();
}
}
public class IndianTea {
public static void main(String args[])
{ Beverage beverage= new MasalaTea();
beverage=new Elaichi(beverage);
System.out.println(beverage.getDescription()+"Rs"+beverage.cost());
}}
Simple Factory :-
Intent: We create an abstraction that decides which of several possible classes to
return and returns one. Then you call the methods of that class instance without
ever knowing which subclass you are actually using. This approach keeps the
issues of data dependence separated from classes useful methods.
import java.util.*;
abstract class Toy {
public abstract void play();
public abstract void stopPlay();
public static Toy factoryMtd(String toyName) throws Exception {
if (toyName.equals("Pokemon"))
return new Pokemon();
if (toyName.equals("SpiderMan"))
return new SpiderMan();
throw new Exception("No toy called " + toyName );
}
}
class Pokemon extends Toy {
Pokemon( ) { }
public void play( ) {
System.out.println("Pokemon is calling the method play");
}
public void stopPlay( ) {
System.out.println("Pokemon is calling the method stopPlay");
}
}
class SpiderMan extends Toy {
SpiderMan() {}
public void play() {
System.out.println("SpiderMan is calling the method play");
}
public void stopPlay() {
System.out.println("SpiderMan is calling the method stopPlay");
}
}
public class FactoryMethodDemo {
public static void main(String args[]) {
String toyNameLst[ ] = {"SpiderMan", "Pokemon“ };
ArrayList toyAryLst = new ArrayList( );
try {
for(int i = 0; i < toyNameLst.length; i++) {
toyAryLst.add(Toy.factoryMtd(toyNameLst[i]));
}
}
catch(Exception e) {
System.out.println(e);
}
Iterator iter = toyAryLst.iterator();
Toy toy = null;
while (iter.hasNext()) {
toy = (Toy)iter.next();
toy.play();
toy.stopPlay();
}
}
}
Difference between RISC and CISC
RISC CISC
Reduced Instruction Set computer Complex Instruction Set
It is used by for example apple. Architecture.
Pipelining can be implemented It is used by for example Intel.
easily Pipelining implementation is not easy
Direct addition is not possible.
Fewer, simpler and faster Direct addition between data in two
Instructions. memory locations. Ex.8085
RISC architecture is not widely Large amount of different and
used complex instructions
At least 75% of the processor use
RISC chips require fewer CISC architecture
transistors and cheaper to
produce. Finally, it's easier to In common CISC chips are relatively
write powerful optimized slow (compared to RISC chips) per
compilers. instruction, but use little (less than
RISC) instructions.
Difference between RISC and CISC

RISC puts a greater burden on the In CISC, software developers no


software. Software developers need to write more lines for the
need to write more lines for the same tasks
same tasks.

Mainly used for real time


Mainly used in normal PC’s,
applications
Workstations and servers

CISC processors cannot have a


large number of registers.

CISC processor executes


microcode instructions.
What is backtracking ?
rainy(seattle). …………. (1)
rainy(rochester). ………….. (2)
cold(rochester). ………….. (3)
snowy(X) :- rainy(X), cold(X)………… (4)
rochester and seattle are the name of places
Our target is to prove goal snowy(X) for some value of X
For this for a particular value of X both should be true rainy(X)
and cold(X)
1)First control will check for X = seattle at line number (4)
It would start from rainy(X) on replacing the value of X by seattle the contol
will see that rainy(seattle) is present or not. Since it is present at line number
(1) this line would be called marked .Then further it would place the value of
X in cold(X) since cold(seattle) is not present the prolog would backtrack to
rainy(X) which was the marked place this is called backtracking and try to
put different value of X so that rainy(X) can be proved true. It would then put
the value of X =rochester in rainy(X) .Since rainy(rochester) is present .The
control would put the value of X = rochester in cold(X) .Since cold(rochester)
is also present . snowy(X) is proved true for X= rochester.
What is cut predicate ?
If we have the following query
Rainy(X) ! Cold(X)

1)First control will check for X = seattle


It would start from rainy(X) on replacing the value of X by seattle the contol will
see that rainy(seattle) is present or not. Since it is present at line number (1) this line
would be called marked .Then further it would place the value of X in cold(X) since
cold(seattle) is not present the prolog would not backtrack to rainy(X) which was the
marked place this is due to the presence of cut predicate (!).

Cut indicates that if backtracking must be applied then the pattern fails . The cut
predicate is used to limit the search space for a solution . The use of cut may eliminate
some valid solutions.
A clause is a disjunction (sum) of literals .
A clause can also be conjunction (multiplication) of literals.
A variable or negation of a variable is a literal.

What is a resolvent ?
A clause is a disjunction of literals for any two clauses C1 and C2 , if there is a
literal L1 in C1 that is complimentary to a literal L2 in C2 then delete L1 and L2
from C1 and C2 respectively and construct the disjunction of the remaining
Clauses. The constructed clause is a resolvent of C1 and C2.

Resolution Theorem : Given two clauses C1 and C2 , a resolvent C of C1 and


C2 is a logical consequence of C1 and C2.
Clause(C1) P V Q V -R (P,Q,etc are literals)( -R means negation of R)
Clause(C2)+ -PV-S VTVU
-----------------------------------------------------
QV-RV-SVTVU (Logical Consequence)
P and –P will get cancel with each other.
P
PQ can be written as -PVQ
Demorgans law :-

-(P^Q)  -P V -Q
^ means AND.
Modus Ponen:- Logical Form of Modus Ponen:-
P P
PQ + -PVQ
-------------------- ---------------------------------
Q Q
------------------- ---------------------------------

Modus Tollens:- Logical Form of Modus Tollens:-


PQ -PVQ
-Q + -Q
-------------------- ---------------------------------
-P -P
------------------- ---------------------------------
Resolution Principle :-
Given a set S of clauses ,a (resolution) deduction of C from S is a finite sequence
C1,C2……CK of clauses such that each C either is a clause in S or a resolvent of
clauses preceding C ; and Ck = C .
A deduction of NULL from S is called a refutation or a proof of S.
It is used to verify that whether an argument is correct or not. It is used in prolog
and it is automatic .

If today is Tuesday , then I have a test in computer science or a test in economics .If
my economics professor is sick , then I will not have test in economics. Today is
tuesday and my economics professor is sick. Therefore I will have a test in computer
Science.
Let Today is Tuesday be represented by T
I have a test in CS be represented by CS , I have a test in economics by E
My economics professor is sick be represented by S
T  ( CS V E) -TVCSVE
S  -E -SV-E
T^S T
-------------------------- S
Therefore CS + -CS
--------------------
NULL
The NULL that we have derived is called refutation or deduction This technique is used by
prolog.
Anut(x,y) :- // It is called a rule in prolog.
female(x) // It is a called a fact in prolog.
sister(x ,z ) // It is a called a fact in prolog.
parent(z ,y ) // It is a called a fact in prolog.
Prolog visualizes the above rule as follows
For All x ,y and z
If x is a female and x is a sister of z and z is a parent of y then x is the anut of y.
The facts present in the program are:-
female(Mary) …………..(1)
sister(Mary , John)………..(2)
parent(John,Joseph)……....(3)
[female(x) ^ sister( x , z) ^ parent (z , y) ]  anut ( x , y ) ]
We want to conclude anut (Mary , Joseph) :-
As the second fact is the first fact of sister and its second parameter is John so prolog
will first substitute the value of z as John .Different values of z may be substituted if more sister
Facts would have been present.
[ female(Mary) ^ sister (Mary ,John) ^ parent (John ,Joseph) ] anut (Mary ,Joseph ) ]
We know that PQ can be written as -PVQ
-female(Mary) V- sister(Mary ,John) V- parent (John ,Joseph) ]Vanut (Mary ,Joseph )
All the negated part will get cancelled with (1) , (2) and (3) respectively we would be
left with anut(Mary , Joseph) that we wanted to prove and this is how prolog works
Here backward chaining is used because we start from the goal and then try to prove the
facts.

You might also like