540 likes | 713 Views
CPS 506 Comparative Programming Languages. Imperative Programming Language Paradigm. Introduction. Oldest and most well-developed paradigm Mirrors computer architecture Series of steps Retrieve input Calculate Produce output Procedural Abstraction Assignments Loops Sequences
E N D
CPS 506Comparative Programming Languages Imperative Programming Language Paradigm
Introduction • Oldest and most well-developed paradigm • Mirrors computer architecture • Series of steps • Retrieve input • Calculate • Produce output • Procedural Abstraction • Assignments • Loops • Sequences • Conditional Statements • Examples • Cobol, Fortran, Ada, Pascal, C, Perl
What Makes a Language Imperative? • In a von Neumann machine memory holds: • Instructions • Data • Intellectual heart: assignment statement • Others: • Conditional branching • Unconditional branch (goto)
Procedural Abstraction • Procedural abstraction allows the programmer to be concerned mainly with a function interface, ignoring the details of how it is computed. • The process of stepwise refinement utilizes procedural abstraction to develop an algorithm starting with a general form and ending with an implementation. • Ex: sort(list, len)
Expressions and Assignment • Assignment statement is fundamental: target = expression • Copy semantics • Expression is evaluated to a value, which is copied to the target; used by imperative languages • Reference semantics • Expression is evaluated to an object, whose pointer is copied to the target; used by object-oriented languages.
There exist vast libraries of functions for most imperative languages. • Partially accounts for the longevity of languages like Fortran, Cobol, and C.
Turing Complete • Integer variables, values, operations • Assignment • If • Goto • Structured programming revolution of 1970s replace the Goto with while loops.
C • C was originally designed for and implemented on the UNIX operating system on the DEC PDP-11, by Dennis Ritchie. • Its parent and grandparent are B and BCPL, respectively. • The operating system, the C compiler, and essentially all UNIX applications programs are written in C. • C is not tied to any particular hardware or system, however, and it is easy to write programs that will run without change on any machine that supports C.
Influences • Multics, PL/I • Application: typesetting documentation • PDP-11: 16-bit minicomputer; 32 KB memory • BCPL: typeless • Portability: big-endian vs. little-endian machines • Good code from a non-optimizing compiler • Hardware support for: ++, --, +=, etc.
General Characteristics • Relatively low level language • Macro facility • Conditional compilation • Lacks: iterators, generics, exception handling, overloading • Assignments are expression; ex: strcpy
Dynamic Allocation int *a; ... a = malloc(sizeof(int) *size); /* ANSI C: a = (int *) malloc(sizeof(int) *size); C++: a = new int[size]; */ /* deallocation left to programmer */
#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*) malloc(sizeof(struct node)); result->kind = binary; result->op = op1; result->term1 = left; result->term2 = right; return result; }
struct node *diff(char x, struct node *root){ struct node *result; switch (root->kind) { case value: result = mknodeval(0); break; case var: result = mknodeval( root->id == x?1:0); break;
case binary: switch (root->op) { case '+': result = mknodebin( Plus, diff(x, root->term1), diff(x, root->term2)); break; ... return result; }
Ada • 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 language • Higher Order Language Working Group
General Characteristics • influencs: Algol, Pascal • large language; case insensitive • unlike C, array indexing errors trapped • type safe • generics • exception handling -- strictly control
type union = record case b : boolean of true : (i : integer); false : (r : real); end; var tagged : union; begin tagged := (b => false, r => 3.375); put(tagged.i); -- error
generic type element is private; type list is array(natural range <>) of element; with function ">"(a, b : element) return boolean; package sort_pck is procedure sort (in out a : list); end sort_pck;
package sort_pck is procedure sort (in out a : list) is begin for i in a'first .. a'last - 1 loop for j in i+1 .. a'last loop if a(i) > a(j) then declare t : element; begin t := a(i); a(i) := a(j); a(j) := t; end; end if;
type Matrix is array (Positive range <> of Float, Positive range <> of Float); function "*" (A, B: Matrix) return Matrix is C: Matrix (A'Range(1), B'Range(2)); Sum: Float; begin if A'First(2) /= B'First(1) or A'Last(2) /= B'Last(1) then raise Bounds_Error; end if;
for i in C'Range(1) loop for j in C'Range(2) loop Sum := 0.0; for k in A'Range(2) loop Sum := Sum + A(i,k) * B(k,j); end loop; Result(i,j) := Sum; end loop; end loop; return C; end "*";
Perl is: • widely used • a scripting language (originally for Unix) • dynamically typed • encourages a variety of styles • supports regular expression pattern matching
Scripting Languages • “glue” • take output from one application and reformat into desired input format for a different application. • most time is spent in the underlying applications. • also used for Web applications
General Characteristics • dynamically typed • default conversion from one type to another (vs. Python) • result is distinct operators; ex: . for string concatenation • types: numbers, strings, regular expressions • dynamic arrays: indexed and associative
String vs. numeric comparisons: 10 < 2 # false - numeric 10 < "2" # false "10" lt "2" # true - string 10 lt "2" # true
Indexed Arrays @a = (2, 3, 5, 7); # size is 4 ... $a[7] = 17; # size is 8; # $a[4:6] are undef @array = (1, 2, 'Hello'); @array = qw/This is an array/; @shortdays = qw/Mon Tue Wed Thu Fri Sat Sun/; print $shortdays[1]; @10 = (1 .. 10); print "@10"; # Prints number starting from 1 to 10
Indexed Arrays @array = (1,2,3); print "Size: ",scalar @array,"\n"; @array = (1,2,3); $array[50] = 4; print "Size: ",scalar @array,"\n"; print "Max Index: ", $#array,"\n"; This will return Size: 51 Max Index: 50
Associative Arrays %d = (“bob” => “3465”, “allen” => “3131”, “rebecca” => “2912”); print $d{“bob”}; # prints 3465
Many different ways of saying the same thing • Much of the syntax is optional; • Perl 5 added support for classes and objects • Great strengths: support for regular expressions • Scalar variables start with a $ • Indexed arrays with an @ • Hash arrays with %
Strings • Double quotes: special characters interpreted • ex: “$a \n” • forms: “ “, qq{ }, qq/ / • Single quotes: special characters uninterpreted • forms: ‘ ‘, q{ }, q/ /
while (<>) { ... } is same as: while ($_ = <STDIN>) { ... } where: <> is read a line returns undef at end of file; undef interpreted as false no subject: $_ if $_ =~ m/pattern/ # implied subject, operator
%hash = ('name' => 'Tom', 'age' => 19); print %hash; nameTomage19 sub display_hash { my (%hash) = @_; foreach (%hash) { print "$_ => $hash{$_}\n"; } }
#! /usr/bin/perl if (@ARGV < 1) { die "Usage mygrep string \n" ; } use strict; my $string = shift(@ARGV); my $ct = 0; my $line; while ($line = <STDIN>) { $ct++; if ($line =~ m/$string/) { print STDOUT $ct, ":\t", $line; } } exit;
Ex: Mailing Grades • typical glue program • student grades kept in a spreadsheet • after each project/test, mail each student her grades • include averages • export data in comma-separated value format (CSV) • CSV format varies by spreadsheet
::Proj1:Test1:::::Total:Average • ::50:100::::::150: • Tucker:atuck@college.edu:48:97:::::145:96.66666666 • Noonan:rnoon@college.edu:40:85:::::125:83.33333333 • Average::88:91:::::135:90
Main program - part 1 • retrieves class designation from command line • opens CSV file for input • or die is a common idiom • declares some useful constants (some should be command line options)
#! /usr/bin/perl use strict; my $class = shift; my $suf = ".csv"; open(IN, "<$class$suf") || die "Cannot read: " . "$class$suf\n"; my $sep = ":"; my $tab = 8;
Main program - part 2 • reads grade column names • reads maximum points for each column • adds 100% to @max array
# read header lines: titles, max grades my @hdr = &readSplit(); my @max = &readSplit(); push(@max, '100%');
Main program - part 3 • loop reads 1 student per iteration (line) • chomp() idiom; irregular • tr deletes “ , ' • tokenizer for Perl • last line pops averages from student array and splits values into columns (printed with each student)
# read students my @student; while (<IN>) { chomp; tr /"'//d; push(@student, $_); } my @ave = split(/$sep/, pop(@student));
Main - part 4 • for loop generates mail, 1 student per iteration • student grades split into columns • subroutine call; & optional • mails averages to script invoker • prints number of student emails generated
# gen mail for each student my $ct = 0; foreach (@student) { my @p = split(/$sep/); $ct += &sendMail(@p); } $ave[1] = $ENV{"USER"}; &sendMail(@ave); print "Emails sent: $ct\n"; exit;
sub readSplit • reads a line; note $_ is global • chomp idiom • tr deletes quotes • splits line and returns array of columns
sub readSplit { $_ = <IN>; chomp; tr /"'//d; my @r = split(/$sep/); return @r; }
sub sendMail • no formal parameters • shift -- call by value • @_ array reference -- call by reference • 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
sub sendMail { my $name = shift; my $email = shift; return 0 unless $email; open(MAIL, "| mail -s '$name Grades' $email") || die "Cannot fork mail: $!\n"; print MAIL "GRADE\t\tYOUR\tMAX\tCLASS\n", "NAME\t\tSCORE\tSCORE\tAVE\n\n";
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 value • print maximum points • print average (rounded)
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 $_; }