1 / 54

CPS 506 Comparative Programming Languages

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

feo
Download Presentation

CPS 506 Comparative Programming Languages

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. CPS 506Comparative Programming Languages Imperative Programming Language Paradigm

  2. 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

  3. What Makes a Language Imperative? • In a von Neumann machine memory holds: • Instructions • Data • Intellectual heart: assignment statement • Others: • Conditional branching • Unconditional branch (goto)

  4. Flowchart

  5. 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)

  6. 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.

  7. There exist vast libraries of functions for most imperative languages. • Partially accounts for the longevity of languages like Fortran, Cobol, and C.

  8. Turing Complete • Integer variables, values, operations • Assignment • If • Goto • Structured programming revolution of 1970s replace the Goto with while loops.

  9. 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.

  10. 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.

  11. General Characteristics • Relatively low level language • Macro facility • Conditional compilation • Lacks: iterators, generics, exception handling, overloading • Assignments are expression; ex: strcpy

  12. 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 */

  13. #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; }

  14. 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;

  15. case binary: switch (root->op) { case '+': result = mknodebin( Plus, diff(x, root->term1), diff(x, root->term2)); break; ... return result; }

  16. 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

  17. General Characteristics • influencs: Algol, Pascal • large language; case insensitive • unlike C, array indexing errors trapped • type safe • generics • exception handling -- strictly control

  18. 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

  19. 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;

  20. 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;

  21. 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;

  22. 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 "*";

  23. Perl is: • widely used • a scripting language (originally for Unix) • dynamically typed • encourages a variety of styles • supports regular expression pattern matching

  24. 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

  25. 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

  26. String vs. numeric comparisons: 10 < 2 # false - numeric 10 < "2" # false "10" lt "2" # true - string 10 lt "2" # true

  27. 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

  28. 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

  29. Associative Arrays %d = (“bob” => “3465”, “allen” => “3131”, “rebecca” => “2912”); print $d{“bob”}; # prints 3465

  30. 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 %

  31. Strings • Double quotes: special characters interpreted • ex: “$a \n” • forms: “ “, qq{ }, qq/ / • Single quotes: special characters uninterpreted • forms: ‘ ‘, q{ }, q/ /

  32. 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

  33. %hash = ('name' => 'Tom', 'age' => 19); print %hash; nameTomage19 sub display_hash { my (%hash) = @_; foreach (%hash) { print "$_ => $hash{$_}\n"; } }

  34. #! /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;

  35. 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

  36. ::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

  37. 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)

  38. #! /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;

  39. Main program - part 2 • reads grade column names • reads maximum points for each column • adds 100% to @max array

  40. # read header lines: titles, max grades my @hdr = &readSplit(); my @max = &readSplit(); push(@max, '100%');

  41. 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)

  42. # read students my @student; while (<IN>) { chomp; tr /"'//d; push(@student, $_); } my @ave = split(/$sep/, pop(@student));

  43. 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

  44. # 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;

  45. sub readSplit • reads a line; note $_ is global • chomp idiom • tr deletes quotes • splits line and returns array of columns

  46. sub readSplit { $_ = <IN>; chomp; tr /"'//d; my @r = split(/$sep/); return @r; }

  47. 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

  48. 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";

  49. 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)

  50. 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 $_; }

More Related