1 / 37

COMPARING LANGUAGES

COMPARING LANGUAGES. Differences Between Languages Lottery Program Example. Major D istinctions B etween Languages. Procedural Languages earliest high-level languages don’t encapsulate data and processing, emphasize functional (task) decomposition FORTRAN C …

cardea
Download Presentation

COMPARING 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. COMPARING LANGUAGES • Differences Between Languages • Lottery Program Example Comparing Languages

  2. Major Distinctions Between Languages • Procedural Languages • earliest high-level languages • don’t encapsulate data and processing, emphasize functional (task) decomposition • FORTRAN • C • … • Object Oriented Languages • SmallTalk • C++ • Java • C# • Functional languages • emphasizes evaluation of functions which depend on only input, and not on the state of the program. • LISP • Scheme • Racket (taught in CS17) • Multiparadigm Languages • support multiple ways of building the structure and elements of a program (OOP, Functional, etc.) • JavaScript • Python • Ruby • Special Purpose Languages • Matlab • Processing Comparing Languages

  3. Common Language Features • Type checking, and how to define complex data? • languages provide access to different types of data • most languages support composite data types (ADTs) • How to modularize code? • most languages allow you to break program into callable code blocks (i.e., subroutines in assembler, procedures in procedural languages, functions in functional languages, methods in object oriented languages) • How to pass parameters to subroutines? • every modern language provides way to parameterize subroutines for generality • How to reuse code you (or someone else) has written before in your program? • every language provides a way to organize your code into reusable modules, and many offer packages / libraries that can act as “out of the box” solutions • How to manage memory? • Some languages have mechanisms for the programmer to manage memory directly, others perform automatic garbage collection • So, even though there are many languages… • can often read programs written in other languages • syntax changes (sometimes wildly), but many concepts remain similar • but fundamental styles and mechanisms may differ considerably, e.g., OOP vs. Functional Comparing Languages

  4. Types • Most languages provide type-checking • for example, cannot assign an int to a Shape • can declare variable’s name and type before use • C intmyAge; /*<type> <variable-name>;*/ • must declare all subroutine variables at top of procedure • Some languages either don’t require types, or can infer type from use of variable • for example: assembler, LISP, MATLAB, Python • allows for more free-style programming style • but easy to introduce errors, hard to debug – classic example of freedom vs. (intrusive) help (kinda like libertarian vs. strong government political philosophies) Comparing Languages

  5. User-defined (Composite) Data Types • “Struct” (for structure) organizes data only • no methods • no access protection (everything is public!!!!!) • C typedefstruct { char name[80]; /* a string */ int year; } TA; /* name of the struct we just defined*/ • accessstruct members using ‘.’ operator TA ta; ta.name = “Jake Rosenfeld”; ta.year = 2; Comparing Languages

  6. MyClass MyReference MyContainee Referenced vs. Contained Data • In Java, there are only references to objects • distinction between referenced (associated) and contained objects is semantic only • many other languages distinguish between references and contained data syntactically (see the bottom of this slide!) • note: base types are not referenced in Java, and are part of memory used for object • Pointers act like references • point to data that is stored elsewhere in memory (in Java, other objects; in C, other base types or complex data types like struct) • Java treats object references like pointers to object instance • In C, there’s a syntactic difference between reference and contained data • contain variables that are assigned some data, or • reference other data using pointers Comparing Languages

  7. Pointer Syntax • C • use “*” to declare pointer or dereference it • use “->” to access member of struct pointed to • use “&” to get address of variable //declarations TA* taPtr; /* pointer to a TA struct */ TA ta; //instructions taPtr = &ta; /* taPtr points to ta */ taPtr->name = “Jake Rosenfeld”; //or ta.name = “Jake Rosenfeld” /* or “dereference” the pointer */ *taPtr.name = “Jake Rosenfeld” Comparing Languages

  8. Subroutines and Parameters • Also called procedures or functions • procedures return no value (like void methods) • in procedural languages, not contained in classes • standard conventions for passing parameters • C • basically like Java, but C has no classes, inheritance intComputeArea(int w, int h) { return w * h; } • In functional programming languages, functions will operate by calling functions within themselves • Typeless languages like Python do not specify a return type. Comparing Languages

  9. Function Structure • Declare before use • unlike Java, order matters in most languages • C doesn’t let you call methods you have not already declared • so in C you can define method separately from declaration /* Declaration */ intComputeArea(int, int) ; int main() { int area; area = ComputeArea(5, 10); return 0; } /* Definition */ intComputeArea(int w, int h) { return w * h; } • Thus, main in C should be defined after all declarations • so they can call any method in program Comparing Languages

  10. Passing Parameters Mechanism • Parameters are said to be passed by value in Java and C • pass in copy of variable instead of variable itself • note: in Java this means copy of reference (i.e., pointer to object), not copy of what it refers to • thus receiver can modify caller’s actual parameter via ref • base types in Java are passed by value (i.e., Java makes copy of passed parameter‘s value when invoking method, instead of just getting memory address of variable) – thus cannot change actual parameter if it is a base type • Parameters can be passed by reference in other languages (like C++) • allows the function change the value of the parameter • Because parameter is not copied, this is very efficient, even when used with large structsor classes • can pass by constreference to avoid unintentional changes Comparing Languages

  11. Memory Management • Java manages memory under the hood, using the Garbage Collector • when a variable goes out of scope, the Garbage Collector releases the memory which held that variable’s data • In other languages, such as C and C++, programmers must manage their own memory • to store data outside scope of a function, programmer must tell language to allocate space to store that data (using the malloc function in C/C++) • on the flip side, when that data is no longer needed, must tell system to release that memory (using the free function in C/C++). • common error: if memory is never released, program will have a memory leak, which decreases performance by reducing amount of available memory for remainder of program’s runtime Comparing Languages

  12. Multithreaded Programming • Most computers have multicore processors, which can concurrently execute instructions • Each core operates on a separate “thread”. • With multithreaded programming, many programs can execute more quickly by instructing each thread to complete a different task – synchronization must be provided if there are task dependencies • Many languages provide support for multithreaded programming. • Java has the java.lang.Thread class which allows the programmer to create and operate more than one thread • C has the POSIX Thread library • You will learn more about multithreaded programming in CS33 and CS32. Comparing Languages

  13. Python • Fully featured, high-level modern language • support for Object Oriented Programming • cross-platform: the same code will run on any computer with python installed—like Java but even more portable • integrates very well with other languages and GUI systems • Interpreted language • not compiled; programs converted to machine code at runtime! • skips compilation but can lead to really nasty bugs at runtime—you won’t find out about errors in a line of code until that line runs • interpreted languages can be slow, though Python is rarely much slower than Java and a program can be optimized once complete to run faster than Java in many circumstances • can be “frozen”—this is similar to compilation and results in an executable • Very different Syntax • Python syntax is noticeably different from most common languages • syntax stresses few lines of code and maximum readability • complex ADT’s like dictionaries and hash-maps are built into the language! • Python is very popular and growing quickly • Python is quickly becoming one of the most popular production programming languages, though still dominated by Java • allows for rapid development and prototyping—code is short and easy to read • ships standard with Linux, Solaris and Apple OSX • used by Google, NASA, Facebook, Apple and many others Comparing Languages

  14. JavaScript • Poorly named: not related to Java in any significant way, especially not in philosophy of compile-time checking • "Wild Wild West":   • lack of compile-time checks, "anything goes", e.g., all instance vars public • impacts runtime stability of the app, but not the underlying file system, OS, etc. • runs in secure sandbox • Does not create applets or stand-alone applications (unlike Java). In its most common form, JavaScript resides inside HTML documents, and can provide levels of interactivity to web pages that are not achievable with simple HTML. Comparing Languages

  15. Browser Framework Comparing Languages

  16. JavaScript syntax • Weakly typed: • Declarations of type (and indeed of variables themselves) are not necessary • Assignment x=y can change the type of x implicitly (e.g., integer to string – very unsafe!) • Encourages/rewards terseness, but can make it difficult to predict behavior and to diagnose failures • Composite data types: • Array • Map (key=>value hashtable) used pervasively e.g. keyword-parameter sets) DrawEllipse( { leftx: 5, topy: 10,      width: 20, height: 200,      color: "red", //default if you omit clickhandler: function(){....} //override }); Comparing Languages

  17. Classes in JavaScript • Object oriented, in an "interesting" way: • "Prototype-based" OO • no declaration of classes • any object X can be "cloned", creating an identical but distinct copy Y (very different from instancing a “template” class def in Java) • in this case, X is the "prototype" acting as the class, and Y is the new instance // A class definition is simply a map variable ClassCoord= {    x: null,   // data member, like an instance variable    y: null, // method: function is value of the "add" keyword    add: function(othercoord) {                 x = x + othercoord.x;  y = y + othercoord.y;     } }; // This is how you instantiate the class coordA = ClassCoord; coordA.x = 5; // instance vars are PUBLIC (OMG!!!) coordA.y = 3; Comparing Languages

  18. JavaScript Subclassing • One advantage of this lack of formality: prototype can be altered at runtime in any way: new members, deletion of members, new methods, replacement of methods, etc.  Thus, class definitions are not static but as fluid as any other data.  • For example, subclassing is simulated in this way:  make a clone of an object representing base class, and then augment/change clone's behaviors to result in desired subclass behaviors • Built-in APIs: • String manipulation • Math package with a large number of functions, e.g. trig, logarithms, etc. • DOM traversing and modification • AJAX • Asynchronous JavaScript and XML • web applications can send/retrieve data from, a serverin the background without interfering with the display and behavior of the existing page. Comparing Languages

  19. JavaScript and the Web • However questionable JS's design philosophy is, its ease of use has grown exponentially creating a very rich ecosystem:  embedded debuggers, powerful IDEs, opensource frameworks/libraries,... • JavaScript has increased its popularity on the web over time. • HTML evolution: • HTML3/4:  Text/static image centric, developers relied on Flash for rich media experiences (games, animations, banner ads, videos) • HTML 5:  Large new set of features brought into browser (and thus necessarily into JavaScript API): • built-in video audio players • dynamic 2D graphics • built-in animation • NODE.JS : JavaScript outside the browser on any machine/OS, for any purpose Comparing Languages

  20. Syntax Examples: Conditionals • JavaScript: • console.log() is equivalent to System.out.println(). if (2>3){ console.log( “bigger”); } else { console.log(“smaller”); } > “smaller” • Scheme/Racket: • evaluates first expression in prefix notation like we saw in the trees lecture. (> 2 3) can be translated to (2 > 3). If first expression in the first parameter is true, return second parameter. Else, return the third parameter. > (if (> 2 3) “bigger” “smaller”) > “smaller” Comparing Languages

  21. Syntax Examples: Functions • JavaScript: function square(x){ return x*x; } >square(7); 49 • Scheme/Racket: • first term after define is similar to the Java method signature: it specifies the name, in this case “square”, and the parameters, in this case “x”. The method can have any number of parameters. The second term after define is similar to Java’s method body. > (define (square x) (* x x)) > (square 7) 49 Comparing Languages

  22. Syntax Examples: Looping • JavaScript: //square contents of array function squareArray(array){ varreturnArray=[];//create array for (vari=0; i<array.length; i++){ returnArray[i]=square(array[i]); } return returnArray; } > var array=[1,2,3,4];//create array > squareArray(array); [1,4,9,16] • Scheme/Racket: • list function returns its parameters as a list of values. • map function iterates over a list, and applies the function specified in the second term, in this case the square, to each element in the list. • on output, a list is represented with an apostrophe, and then the list’s values in between parentheses. > (map square (list 1 2 3 4)) ‘(1 4 9 16) Comparing Languages

  23. New languages made every day! Comparing Languages

  24. LOTTERY in Multiple Languages • Pseudocode • Java • Python • C (and by extension C++) • FORTRAN Comparing Languages

  25. Lottery Program Specification • Let’s write the same (procedural) program in different languages • was a warmup assignment in CS11 (the old name for CS15) for 15 years Write a program that takes pairs of integers representing the value of a prize and the number of that prize to be awarded. The last entry should be denoted by a negative or zero prize value. Output the cost of each prize, and the total prize. Also issue a warning if the total cost exceeds $450,000. • We will look mainly at Java, C, Python, and FORTRAN Comparing Languages

  26. PSEUDO-CODE get initial value of current_prize from user’s input get initial value of current_winners from user’s input while current_prize> 0 current_payoff = current_prize * current_winners total_payoff = total_payoff + current_payoff total_winners = total_winners + current_winners write current_winners and current_payoff to screen get current_prize from user’s input get current_winnersfrom user’s input write total_payoff to screen write total_winners to screen if total_payoff > maximum_payoff then write bad payoff message to screen Comparing Languages

  27. Wait a minute … how do we handle input? • Can think of many scenarios where we want to read contents of some file or ask user to supply us with information via command line • How do we handle this input in Java? • Answer: with streams! • You can think of streams as some sequence of bytes flowing from one source (such as a file or command line input) to some destination (i.e., your program) • It can be messy to deal with raw byte data directly • have to define how many bytes to read in at a time • have to explicitly allocate memory to store each sequence of bytes we read in • there has to be a better way … Comparing Languages

  28. Handling Input (Cont’d) • java.io.Reader! • abstract class defined by Java that defines subclasses to access the contents of some file or user input via command line • converts the raw byte data into character data that human beings can understand • one common practice is to make BufferedReaderby constructing it with an InputStreamReader(both are subclasses of Reader) so that we convert bytes to characters, and then read characters line by line using readLine() • Construct an InputStreamReaderby passing it some InputStream • often times FileInputStream for reading files, or System.infor console input • Then, construct a BufferedReaderthat takes in an InputStreamReader • and voila! Instant line-reading functionality Comparing Languages

  29. JAVA (1/3) import java.io.BufferedReader; import java.io.InputStreamReader; public class Lottery { public static final int MAX_PAYOFF = 450000; public static void main(String argv[]) { int prize, // value of prize being read winners, // number of winners for a // particular prize payoff, // how much paying off a // particular prize will cost tot_win, // total number of winners tot_pay; // total amount spent on paying // off prizes BufferedReader input = new BufferedReader( new InputStreamReader(System.in)); tot_win = 0; tot_pay= 0; prize = 0; winners = 0; System.out.println(“PRIZE WINNER’S PAYOFF”); Comparing Languages

  30. JAVA (2/3) // Let’s make sure we’re reading in integers! try { prize = Integer.parseInt(input.readLine()); winners = Integer.parseInt(input.readLine()); } catch (java.io.IOExceptionexc) { System.out.println(“Error reading input”); } // as long as the inputted value is > 0 … while (prize > 0) { payoff = prize * winners; tot_pay += payoff; tot_win += winners; System.out.println(prize + “ “ + winners + “ “ + payoff); try { prize = Integer.parseInt(input.readLine()); winners = Integer.parseInt(input.readLine()); } catch (java.io.IOExceptionexc) { System.out.println(“Error reading input”); } } // end of while loop Comparing Languages

  31. JAVA (3/3) // After a negative value is entered, print out // the total payoff and total winners System.out.println(“Total payoff = “ + tot_pay + “\n” + “Total winners “ + tot_win); if (tot_pay > MAX_PAYOFF){ System.out.println(“*** Bad payoff: greater than $” + MAX_PAYOFF); } } // end of class Lottery Comparing Languages

  32. Python import sys #like java import max_payoff = 450000 #note lack of declared type prize = int(raw_input("Enter initial prize:")) winners = int(raw_input( "Enter initial winners:")) tot_pay = prize #no semicolons needed either! tot_win = winners #note the lack of brackets while prize > 0: #indentation matters!  payoff = prize * winnerstot_pay += payofftot_win += winners   print "prize: ", prize,\ " winners: ", winners,\ " payoff: ", payoff prize = int(raw_input("Enter new prize val:"))  winners = int(raw_input("Enter new winners:")) print “total payoff: ”, tot_pay,\ “total winners: ”, tot_win if payoff > max_payoff: print "***Bad payoff: ", payoff,\ " is greater than: ", max_payoff Comparing Languages

  33. C (and by extension C++) (1/2) #include <stdio.h> /* works like a Java constant */ #define MAX_PAYOFF 450000 /* Fancy routine to show off C’s pointers */ void init(int *tot_win_ptr, int *tot_pay_ptr) { printf(“PRIZE WINNERS PAYOFF\n”); *tot_win_ptr = 0; *tot_pay_ptr = 0; /*Set them to zero*/ } main() { int prize, /* value of prize being read */ winners, /* number of winners for particular prize */ payoff, /* how much paying off a particular prize will cost */ tot_win, /* total number of winners */ tot_pay; /* total amount spent on paying off prizes */ Comparing Languages

  34. C (and by extension C++) (2/2) /* sending addresses of integers */ init(&tot_win, &tot_pay); /* Read input */ scanf(“ %d %d”, &prize, &winners); /* As long as the inputted value is > 0 … */ while (prize > 0) { payoff = prize * winners; tot_pay += payoff; tot_win += winners; printf(“%d %d %d\n”, prize, winners, payoff); scanf(“ %d %d”, &prize, &winners); } /* Print the total payoff and number of winners*/ printf(“\nTotal payoff = %d\nTotal winners = %d\n\n”, tot_pay, tot_win); if (tot_pay > MAX_PAYOFF){ printf(“*** Unsatisfactory payoff: greater than $%d ***\n”, MAX_PAYOFF); } } Comparing Languages

  35. FORTRAN (1/2) INTEGER PRIZE INTEGER WINNERS INTEGER PAYOFF INTEGER TOTPAY INTEGER TOTWIN TOTPAY = 0 TOTWIN = 0 WRITE(6, 100) 100 FORMAT(‘ PRIZE WINNERS PAYOFF’) READ(5, *) PRIZE, WINNERS C C WHILE PRIZE IS POSITIVE C 10 IF (PRIZE.LE.0) GOTO 20 PAYOFF = PRIZE * WINNERS TOTPAY = TOTPAY + PAYOFF Comparing Languages

  36. FORTRAN (2/2) TOTWIN = TOTWIN + WINNERS WRITE(6, 110) PRIZE, WINNERS, PAYOFF 110 FORMAT(3I8) READ(5, *) PRIZE, WINNERS C C ENDWHILE C GOTO 10 20 WRITE(6, 210) TOTPAY 210 FORMAT(‘TOTAL PAYOFF =‘, I10) WRITE(6,220) TOTWIN 220 FORMAT(‘TOTAL WINNERS = ‘, I10) IF (TOTPAY.GT.450000) THEN WRITE(6, 120) 120 FORMAT(‘*** UNSATISFACTORY PAYOFF GREATER THAN $450,000’) ENDIF STOP END Comparing Languages

  37. Announcements • Tetris on time handin is next Thursday, 11/21, at 11:59pm. • Early: Tuesday, 11/19, 11:59pm • Late: Saturday, 11/23, 10:00pm • Make sure to complete Data Structures II this week– it’s your last CS15 lab EVER!  • Final projects come out on Tuesday! They’ll be due 12/19 at 5pm (you have a whole month). Comparing Languages

More Related