CPS 506 Comparative Programming Languages - …ssamet/cps506/CPS 506 (Winter 2010 Ryerson...CPS 506...

54
CPS 506 Comparative Programming L Languages Imperative Imperative Programming Language P di Paradigm

Transcript of CPS 506 Comparative Programming Languages - …ssamet/cps506/CPS 506 (Winter 2010 Ryerson...CPS 506...

CPS 506Comparative Programming

LLanguagesImperativeImperative

Programming Language P diParadigm

IntroductionIntroductionOld t d t ll d l d di• Oldest and most well-developed paradigm

• Mirrors computer architectureS i f • Series of steps– Retrieve input

Calculate– Calculate– Produce output

• Procedural AbstractionProcedural Abstraction– Assignments– Loops– Sequences– Conditional Statements

E l• Examples– Cobol, Fortran, Ada, Pascal, C, Perl 2

What Makes a Language g gImperative?

I N hi • In a von Neumann machine memory holds:– Instructions– DataData

• Intellectual heart: assignment statement– Others:Others:

• Conditional branching• Unconditional branch (goto)• Unconditional branch (goto)

3

FlowchartFlowchart

4

Procedural AbstractionProcedural AbstractionP d l b ll h • Procedural abstraction allows the programmer to be concerned mainly with a function

f h d l f h interface, ignoring the details of how it is computed.

• The process of stepwise refinement utilizes The process of stepwise refinement utilizes procedural abstraction to develop an algorithm starting with a general form and algorithm starting with a general form and ending with an implementation.– Ex: sort(list len)Ex: sort(list, len)

5

Expressions and AssignmentExpressions and AssignmentA i t t t t i f d t l• Assignment statement is fundamental:target = expressionp

• Copy semantics• Expression is evaluated to a value, which is E p n u u , w

copied to the target; used by imperative languages

• Reference semantics• Expression is evaluated to an object, whose p j

pointer is copied to the target; used by object-oriented languages.

6

h l b f f f • There exist vast libraries of functions for most imperative languages.

• Partially accounts for the longevity of languages like Fortran, Cobol, and C.g g

7

Turing CompleteTuring Complete

I t i bl l ti• Integer variables, values, operations• Assignmentg m• If

G t• Goto

• Structured programming revolution of 1970s replace the Goto with while of 1970s replace the Goto with while loops.

8

CCC was originally designed for and • C was originally designed for and implemented on the UNIX operating system on the DEC PDP-11, by Dennis Ritchie.on the DEC PDP , by Denn s R tch e.

• Its parent and grandparent are B and BCPL, respectively.p y

• The operating system, the C compiler, and essentially all UNIX applications programs are written in Care written in C.

• C is not tied to any particular hardware or system however and it is easy to write system, however, and it is easy to write programs that will run without change on any machine that supports C.

9

InfluencesInfluencesM lti PL/I• Multics, PL/I

• Application: typesetting documentationpp yp• PDP-11: 16-bit minicomputer; 32 KB

memoryy• BCPL: typeless• Portability: big-endian vs little-endian • Portability: big-endian vs. little-endian

machines• Good code from a non optimizing compiler• Good code from a non-optimizing compiler• Hardware support for: ++, --, +=, etc.

10

General CharacteristicsGeneral CharacteristicsR l ti l l l l l• Relatively low level language

• Macro facilityy• Conditional compilation• Lacks: iterators generics exception Lacks: iterators, generics, exception

handling, overloading• Assignments are expression; ex: strcpy• Assignments are expression; ex: strcpy

11

Dynamic AllocationDynamic Allocationi *int *a;...a = malloc(sizeof(int) *size);/* ANSI C: a = (int *) malloc(sizeof(int) *size);

C++: a = new int[size]; *//* deallocation left to programmer */

12

#include <stdio.h>#include <stdlib.h>#include "node.h"struct node *mknodebin(char op1, struct node *left,struct node * right) {

struct node *result;result = (struct node*)ll ( i f( t t d ))malloc(sizeof(struct node));

result->kind = binary;result->op = op1;result->op = op1;result->term1 = left;result->term2 = right;result >term2 right;return result;

}}

13

struct node *diff(char x, struct node *root){

t t d * ltstruct node *result;switch (root->kind) {

l lt k d l(0)case value: result = mknodeval(0);break;

case var:result = mknodeval(

root->id == x?1:0);break;

14

case binary:switch (root->op) {

'+'case '+':result = mknodebin(

PlusPlus,diff(x, root->term1),diff(x, root->term2));diff(x, root >term2));

break;...return result;

}

15

AdaAdad l d i l t 1970’ b US • developed in late 1970’s by US Department of Defense (DoD)

• DoD spending billions of dollars on software

• over 450 languages in use• solution: standardize on one languagesolution standardize on one language• Higher Order Language Working Group

16

General CharacteristicsGeneral Characteristicsi fl Al l P l• influencs: Algol, Pascal

• large language; case insensitive• unlike C, array indexing errors trapped• type safetype safe• generics

exception handlin strictly control• exception handling -- strictly control

17

type union =record

b b l fcase b : boolean oftrue : (i : integer);false : (r : real);false : (r : real);

end;var tagged : union;var tagged : union;begin tagged := (b => false, r => 3.375);

put(tagged.i); -- errorp ( gg )

18

igenerictype element is private;type list is array(natural range <>) oftype list is array(natural range <>) of element;with function ">"(a, b : element) return b lboolean;

package sort pck ispackage sort_pck isprocedure sort (in out a : list);

end sort_pck;

19

k t k ipackage sort_pck isprocedure sort (in out a : list) isbegin

for i in a'first .. a'last - 1 loopfor j in i+1 .. a'last loop

if a(i) > a(j) thenif a(i) > a(j) thendeclare t : element;begin

t := a(i);a(i) := a(j);a(j) := t;a(j) : t;

end;end if;

20

type Matrix isarray (Positive range <> of Float,

Positive range <> of Float);function "*" (A, B: Matrix) return Matrix iisC: Matrix (A'Range(1), B'Range(2));Sum: Float;Sum: Float;

beginif A'First(2) /= B'First(1) orif A First(2) /= B First(1) or

A'Last(2) /= B'Last(1) thenraise Bounds Error;raise Bounds_Error;

end if;

21

f i i C'R (1) lfor i in C'Range(1) loopfor j in C'Range(2) loop

Sum := 0 0;Sum : 0.0;for k in A'Range(2) loop

Sum := Sum + A(i,k) * B(k,j);end loop;Result(i,j) := Sum;

d lend loop;end loop;return C;return C;

end "*";

22

P l i• Perl is:• widely used• widely used• a scripting language (originally

f )for Unix)• dynamically typeddynamically typed• encourages a variety of styles• supports regular expression

pattern matchingpattern matching23

Scripting LanguagesScripting Languages

• “glue”take output from one application • take output from one application and reformat into desired input pformat for a different applicationapplication.

• most time is spent in the punderlying applications.l d f W b li i• also used for Web applications

24

General CharacteristicsGeneral Characteristicsd ll d• dynamically typed

• default conversion from one type to f u f m ypanother (vs. Python)

• result is distinct operators; ex: for string • result is distinct operators; ex: . for string concatenation

b l • types: numbers, strings, regular expressions

• dynamic arrays: indexed and associative

25

St i i i• String vs. numeric comparisons:10 < 2 # false - numeric10 < "2" # false10 < 2 # false"10" lt "2" # true - string10 lt "2" # true

26

• Indexed Arrays• Indexed Arrays@a = (2, 3, 5, 7); # size is 4...$a[7] = 17; # size is 8;

# $a[4:6] are undef

@ (1 2 'H ll ')@array = (1, 2, 'Hello');@array = qw/This is an array/;

@shortdays qw/Mon Tue Wed Thu Fri Sat Sun/;@shortdays = qw/Mon Tue Wed Thu Fri Sat Sun/;print $shortdays[1];

@10 = (1 10);@10 = (1 .. 10);print "@10"; # Prints number starting from 1 to 10

27

I d d A• Indexed Arrays@array = (1,2,3);print "Size: " scalar @array "\n";print Size: ,scalar @array, \n ;

@array = (1,2,3);$array[50] = 4;

print "Size: ",scalar @array,"\n";print Size: ,scalar @array, \n ;print "Max Index: ", $#array,"\n";

This will returnSize: 51Max Index: 50Max Index: 50

28

A i ti A• Associative Arrays%d = (“bob” => “3465”,

“allen” => “3131”,“rebecca” => “2912”);

print $d{“bob”}; # prints 3465

29

M diff t s f s i th s m • Many different ways of saying the same thing

• Much of the syntax is optional;• Much of the syntax is optional;• Perl 5 added support for classes and

objectsobjects• Great strengths: support for regular

expressionsexpressions• Scalar variables start with a $• Indexed arrays with an @• Indexed arrays with an @• Hash arrays with %

30

StringsStringsD bl t i l h t • Double quotes: special characters interpreted

– ex: “$a \n”– forms: “ “, qq{ }, qq/ /qq qq

• Single quotes: special characters uninterpreteduninterpreted– forms: ‘ ‘, q{ }, q/ /

31

while (<>) { }while (<>) { ... }

is same as:while ($ = <STDIN>) { }while ($_ = <STDIN>) { ... }

where:is d lin<> is read a line

returns undef at end of file; undef i d f linterpreted as falseno subject: $_jif $_ =~ m/pattern/ # implied subject, operator

32

%hash ('name' > 'Tom' 'age' > 19);%hash = ('name' => 'Tom', 'age' => 19);print %hash;

nameTomage19

sub display hashsub display_hash{

my (%hash) = @_;foreach (%hash){

print "$ => $hash{$ }\n";print $_ > $hash{$_}\n ;}

}

33

#! /usr/bin/perl#! /usr/bin/perlif (@ARGV < 1) { die "Usage mygrep string \n" ; }

iuse strict;my $string = shift(@ARGV);my $ct = 0;my $ct 0;my $line;while ($line = <STDIN>) {

$ct++;if ($line =~ m/$string/) {

i t STDOUT $ t " \t" $liprint STDOUT $ct, ":\t", $line;}

}}exit;

34

Ex: Mailing GradesEx: Mailing Grades• typical glue program

• student grades kept in a spreadsheetg p p• after each project/test, mail each student her

gradesgrades• include averages

d d l f • export data in comma-separated value format (CSV)

• CSV format varies by spreadsheet

35

j1 1 l• ::Proj1:Test1:::::Total:Average• ::50:100::::::150:

@• Tucker:[email protected]:48:97:::::145:96.66666666

• Noonan noon@college ed 40 85 125• Noonan:[email protected]:40:85:::::125:83.33333333

• Average::88:91:::::135:90• Average::88:91:::::135:90

36

M i t 1• Main program - part 1• retrieves class designation from retrieves class designation from

command line• opens CSV file for input• opens CSV file for input• or die is a common idiom• declares some useful constants (some

should be command line options)p )

37

#! /usr/bin/perl#! /usr/bin/perl

use strict;use strict;my $class = shift;

$ f " "my $suf = ".csv";open(IN, "<$class$suf") || die "Cannot read: " "$class$suf\n";read: . $class$suf\n ;

my $sep = ":";my $tab = 8;my $tab = 8;

38

M i t 2• Main program - part 2• reads grade column namesreads grade column names• reads maximum points for each

columncolumn• adds 100% to @max array

39

# d h d li titl d# read header lines: titles, max gradesmy @hdr = &readSplit();

@ dS lit()my @max = &readSplit();push(@max, '100%');

40

M i t 3• Main program - part 3• loop reads 1 student per iteration loop reads 1 student per iteration

(line)• chomp() idiom; irregular• chomp() idiom; irregular• tr deletes “ , '• tokenizer for Perl• last line pops averages from student last line pops averages from student

array and splits values into columns (printed with each student)(printed with each student)

41

# d d# read studentsmy @student;iwhile (<IN>) {

chomp;/ //tr /"'//d;

push(@student, $_);}my @ave = split(/$sep/, pop(@student));

42

M i t 4• Main - part 4• for loop generates mail, 1 student per for loop generates mail, 1 student per

iteration• student grades split into columnsstudent grades split into columns• subroutine call; & optional

mails avera es to script invoker• mails averages to script invoker• prints number of student emails

generated

43

# il f h t d t# gen mail for each studentmy $ct = 0;f h (@ t d t) {foreach (@student) {

my @p = split(/$sep/);$ d il(@ )$ct += &sendMail(@p);

}$ 1 $$ave[1] = $ENV{"USER"};&sendMail(@ave);

\print "Emails sent: $ct\n";exit;

44

b dS lit • sub readSplit • reads a line; note $ is globalreads a line; note $_ is global• chomp idiom

t d l t s t s• tr deletes quotes• splits line and returns array of p y

columns

45

b d li {sub readSplit {$_ = <IN>;chomp;tr /"'//d;

/ /my @r = split(/$sep/);return @r;

}

46

b dM il • sub sendMail • no formal parameters

h f ll b l• shift -- call by value• @_ array reference -- call by reference

f d h l dd• return if student has no email address• open pseudo file or die

• MAIL is a pipe to Berkeley mail command• s option is subject• $email is mail address

47

sub sendMail {my $name = shift;my $name shift;my $email = shift;return 0 unless $email;

i $ $ iopen(MAIL, "| mail -s '$name Grades' $email")|| die "Cannot fork mail: $!\n";

print MAIL "GRADE\t\tYOUR\tMAX\tCLASS\n",p ,"NAME\t\tSCORE\tSCORE\tAVE\n\n";

48

b dM il f l• sub sendMail -- for loop• for each column• skip column if empty header -- not a grade• otherwise print header• if column value starts with a digit, round

value to an integer; otherwise print valuei i i• print maximum points

• print average (rounded)

49

my $ct = 1;my $ct = 1;

foreach (@_) {

$ct++;next unless $hdr[$ct];print MAIL "$hdr[$ct]\t";print MAIL "\t" if length($hdr[$ct]) < $tab;

if (/^\d/) { print MAIL int($_ + 0.5); }

else { print MAIL $_; }

50

i t MAIL "\t$ [$ t]\t"print MAIL "\t$max[$ct]\t";if ($ave[$ct] =~ /^\d/) {

print MAIL int($ave[$ct] + 0.5); } else { print MAIL $ave[$ct];}print MAIL "\n";

} # foreachreturn 1;

} # sub sendMail

51

$ i li d bj t/ bj t• $_ : implied object/subject• $ARG : default input• $. : input line number• $/ : input record separator : default \np p

– undef $/; $_ = <IN>; # reads entire file• $, : output field separator in print$, output field separator in print• $\ : output record separator• $" : list separator : default space• $ : list separator : default space• $[ : starting array index : default zero

52

Regular ExpressionsRegular ExpressionsO t• Operators

• m// -- match, m optionalp• s/// -- substitute• split -- array returning functionsplit array returning function

53

M difi• Modifiers• i -- case insensitive• m -- treat string as multiple lines• s -- treat string as a single lines treat string as a single line• x -- extend with whitespace and comments

54