CS307: Principles of Programming Languages

Total Page:16

File Type:pdf, Size:1020Kb

CS307: Principles of Programming Languages CS307: Principles of Programming Languages LECTURE 12: NAMES, SCOPES, AND BINDINGS II LECTURE OUTLINE • INTRODUCTION • BINDINGS • LIFETIME AND STORAGE MANAGEMENT • SCOPE RULES • STATIC SCOPING • DYNAMIC SCOPING • STATIC VS DYNAMIC SCOPING • DEEP VS SHALLOW BINDING • POLYMORPHISM, DYNAMIC BINDING, GENERIC PROGRAMMING • METHOD MATCHING VS BINDING • BINDING OF REFERENCE ENVIRONMENTS • SEPARATE COMPILATION 2 CS307 : Principles of Programming Languages - (c) Paul Fodor (CS Stony Brook), Tony Mione (SUNY Korea) and Pearson SCOPE RULES • BINDING SCOPE IS THE TEXTUAL REGION OF THE PROGRAM IN WHICH A BINDING IS ACTIVE • A SCOPE IS A PROGRAM SECTION OF MAXIMAL SIZE WHERE • NO BINDINGS CHANGE • MINIMALLY: NO RE-DECLARATIONS ARE PERMITTED • SCOPING RULE EXAMPLE 1: DECLARATION BEFORE USE • CAN A NAME BE USED BEFORE IT IS DECLARED? • JAVA LOCAL VARS: NO • JAVA CLASS PROPERTIES AND METHODS: YES • THE SCOPE OF A BINDING IS DETERMINED STATICALLY OR DYNAMICALLY 3 CS307 : Principles of Programming Languages - (c) Paul Fodor (CS Stony Brook), Tony Mione (SUNY Korea) and Pearson SCOPING RULES • SCOPING RULE EXAMPLE 2: TWO USES OF A GIVEN NAME. DO THEY REFER TO THE SAME BINDING? a = 1 ... def f(): a = 2 b = a SCOPING RULES DETERMINE WHETHER OR NOT THIS IS THE CASE 4 CS307 : Principles of Programming Languages - (c) Paul Fodor (CS Stony Brook), Tony Mione (SUNY Korea) and Pearson SCOPE RULES • KEY IDEA: IN STATIC SCOPE RULES -> BINDINGS DEFINED BY THE PHYSICAL (LEXICAL) STRUCTURE OF THE PROGRAM • STATIC SCOPING (ALSO CALLED LEXICAL SCOPING) EXAMPLES: • ONE BIG SCOPE: (BASIC) • SCOPE OF A FUNCTION (VARIABLES LIVE THROUGH A FUNCTION EXECUTION) • BLOCK SCOPE • NESTED SUBROUTINES • VARIABLES ACTIVE IN ONE OR MORE SCOPES • CLOSEST NESTED SCOPE RULE APPLIES • LEXICAL/STATIC SCOPING WAS USED BY ALGOL 5 • PICKED UP IN MOST LANGUAGES SINCE: (PASCAL, C, JAVA, ETC) CS307 : Principles of Programming Languages - (c) Paul Fodor (CS Stony Brook), Tony Mione (SUNY Korea) and Pearson SCOPE RULES • IN MOST LANGUAGES WITH SUBROUTINES: • OPEN A NEW SCOPE ON SUBROUTINE ENTRY: • CREATE BINDINGS FOR NEW LOCAL VARIABLES • DEACTIVATE BINDINGS FOR GLOBAL VARIABLES THAT ARE RE-DECLARED • THESE [GLOBAL] VARIABLES ARE SAID TO HAVE A "HOLE" IN THEIR SCOPE • ON SUBROUTINE EXIT: • DESTROY BINDINGS FOR LOCAL VARIABLES • REACTIVATE BINDINGS FOR DEACTIVATED GLOBAL VARIABLES 6 CS307 : Principles of Programming Languages - (c) Paul Fodor (CS Stony Brook), Tony Mione (SUNY Korea) and Pearson SCOPE RULES • ELABORATION • PROCESS OF CREATING BINDINGS WHEN ENTERING A SCOPE • STORAGE MAY BE ALLOCATED • TASKS STARTED • EXCEPTIONS MAY BE PROPAGATED AS A RESULT OF THE ELABORATION OF DECLARATIONS 7 CS307 : Principles of Programming Languages - (c) Paul Fodor (CS Stony Brook), Tony Mione (SUNY Korea) and Pearson STATIC SCOPING • STATIC (LEXICAL) SCOPE RULES • A SCOPE IS DEFINED IN TERMS OF THE PHYSICAL (LEXICAL) STRUCTURE OF THE PROGRAM: • SCOPES CAN BE DETERMINED BY COMPILER • ALL BINDINGS FOR IDENTIFIERS CAN BE RESOLVED BY EXAMINING PROGRAM • TYPICALLY, CHOOSE THE MOST RECENT, ACTIVE BINDING MADE AT COMPILE TIME • MOST COMPILED LANGUAGES, C, PASCAL, JAVA AND PYTHON INCLUDED, EMPLOY STATIC SCOPE RULES 8 CS307 : Principles of Programming Languages - (c) Paul Fodor (CS Stony Brook), Tony Mione (SUNY Korea) and Pearson STATIC SCOPING • NESTED BLOCKS: • CLASSICAL EXAMPLE OF STATIC SCOPE RULES: “MOST CLOSELY NESTED RULE”: • AN IDENTIFIER IS • KNOWN IN THE SCOPE IN WHICH IT’S DECLARED AND IN EACH ENCLOSED SCOPE • UNLESS RE-DECLARED IN AN ENCLOSED SCOPE (ORIGINAL IDENTIFIER IS HIDDEN) • TO RESOLVE A REFERENCE TO AN IDENTIFIER: EXAMINE LOCAL SCOPE AND STATICALLY ENCLOSING SCOPES UNTIL A BINDING IS FOUND • CLASSES (IN ABSTRACTION AND OO LANGUAGES) HAVE EVEN MORE SOPHISTICATED (STATIC) SCOPE RULES 9 CS307 : Principles of Programming Languages - (c) Paul Fodor (CS Stony Brook), Tony Mione (SUNY Korea) and Pearson ILLUSTRATION Pascal: CS307 : Principles of Programming Languages - (c) Paul Fodor (CS Stony Brook), Tony Mione 10 (SUNY Korea) and Pearson STATIC SCOPING • SIMPLEST WAY TO FIND FRAMES OF SURROUNDING SCOPES • MAINTAIN A STATIC LINK IN EACH FRAME • POINTS TO THE ‘PARENT’ FRAME: THE FRAME OF MOST RECENT INVOCATION OF A LEXICALLY SURROUNDING SUBROUTINE • SUBROUTINE DECLARED AT OUTERMOST NESTING WILL HAVE A NULL STATIC LINK TO ‘PARENT’ AT RUN TIME • SUBROUTINE NESTED K LEVELS DEEP • FRAME’S STATIC ‘PARENT’ LINK AND THOSE OF GRANDPARENT, ETC. FORM A STATIC CHAIN OF LENGTH K AT RUN TIME 11 CS307 : Principles of Programming Languages - (c) Paul Fodor (CS Stony Brook), Tony Mione (SUNY Korea) and Pearson ILLUSTRATION Nesting of subroutines: During run time (with links) CS307 : Principles of Programming Languages - (c) Paul Fodor (CS Stony Brook), Tony Mione 12 (SUNY Korea) and Pearson STATIC SCOPING • DECLARATION ORDER: • SOME EARLY LANGUAGES, (ALGOL 60, LISP, ETC), REQUIRED ALL DECLARATIONS APPEAR AT BEGINNING OF SCOPE • PASCAL REQUIREMENT: NAMES MUST BE DECLARED BEFORE USED • STILL USES A WHOLE-BLOCK SCOPE (ALSO IMPLEMENTED IN C#) • EXAMPLE (C#): DEFINING VARIABLE IN A BLOCK MAKES EVERY EXTERNAL DECLARATION HIDDEN • ➔ THE M=N ASSIGNMENT GENERATES A COMPILING ERROR! 13 CS307 : Principles of Programming Languages - (c) Paul Fodor (CS Stony Brook), Tony Mione (SUNY Korea) and Pearson DYNAMIC SCOPING • DYNAMIC SCOPE RULES • BINDINGS DEPEND ON CURRENT STATE OF PROGRAM EXECUTION • CANNOT BE RESOLVED BY EXAMINING PROGRAM SOURCE SINCE THEY’RE DEPENDENT ON CALLING SEQUENCES • BINDING MIGHT DEPEND ON HOW A FUNCTION IS CALLED • TO RESOLVE A REFERENCE: USE THE MOST RECENT, ACTIVE BINDING MADE AT RUN TIME 14 CS307 : Principles of Programming Languages - (c) Paul Fodor (CS Stony Brook), Tony Mione (SUNY Korea) and Pearson DYNAMIC SCOPING OF BINDINGS EXAMPLE: var total = 0 def add(): total += 1 def myfunc(): var total = 0 add() add() myfunc() print total VERY EASY TO IMPLEMENT (STACK OF NAMES) OFTEN HARD TO MAKE EFFICIENT CS307 : Principles of Programming Languages - (c) Paul Fodor (CS Stony Brook), Tony Mione 15 (SUNY Korea) and Pearson SCOPE RULES • DYNAMIC SCOPE RULES USUALLY IN INTERPRETED LANGUAGES • EXAMPLES: LISP, PERL, RUBY, C#, THE SHELL LANGUAGES BASH, DASH, AND POWERSHELL • SUCH LANGUAGES DO NOT ALWAYS HAVE COMPILE TIME TYPE CHECKING • TYPE DETERMINATION NOT ALWAYS POSSIBLE WITH DYNAMIC SCOPE RULES 16 CS307 : Principles of Programming Languages - (c) Paul Fodor (CS Stony Brook), Tony Mione (SUNY Korea) and Pearson BINDING OF REFERENCE ENVIRONMENTS • REFERENCE ENVIRONMENT • ALL BINDINGS ACTIVE AT A GIVEN TIME • TO TAKE A REFERENCE TO A FUNCTION • NEED TO DECIDE WHICH REFERENCE ENVIRONMENT TO USE!! • DEEP BINDING BINDS ENVIRONMENT AT TIME PROCEDURE IS PASSED AS AN ARGUMENT • SHALLOW BINDING BINDS ENVIRONMENT AT THE TIME THE PROCEDURE IS ACTUALLY CALLED 17 CS307 : Principles of Programming Languages - (c) Paul Fodor (CS Stony Brook), Tony Mione (SUNY Korea) and Pearson EXAMPLE: STATIC VS. DYNAMIC SHALLOW VS. DYNAMIC DEEP CS307 : Principles of Programming Languages - (c) Paul Fodor (CS Stony Brook), Tony Mione 18 (SUNY Korea) and Pearson BINDING OF REFERENCE ENVIRONMENTS x: integer := 1 y: integer := 2 -DYNAMIC SCOPING WITH DEEP BINDING: -WHEN ADD IS PASSED INTO SECOND procedure add ENVIRONMENT OF ADD IS x = 1, y = 3 x := x + y -THE x IS THE GLOBAL x SO IT WRITES 4 INTO THE GLOBAL x, procedure second(P:procedure) -GLOBAL x IS THE ONE PICKED UP x:integer := 2 BY THE write_integer P() -SHALLOW BINDING: procedure first -JUST TRAVERSE UP CALL CHAIN y:integer := 3 -IT FINDS THE NEAREST VARIABLE second(add) THAT CORRESPONS TO THE NAME (THE LOCAL x) first() -INCREMENTS LOCAL x SO write_integer(x) ANSWER IS 1 CS307 : Principles of Programming Languages - (c) Paul Fodor (CS Stony Brook), Tony Mione 19 (SUNY Korea) and Pearson SCOPE RULES EXAMPLE: STATIC VS. DYNAMIC program scopes (input, output ); • PROGRAM OUTPUT DEPENDS var a : integer; • ON SCOPE RULES procedure first(); begin • IN THE CASE OF DYNAMIC SCOPING, A VALUE READ AT RUN TIME a := 1; end; • STATIC SCOPING: THIS PROGRAM PRINTS A 1. procedure second(); • DYNAMIC SCOPING: var a : integer; • OUTPUT DEPENDS ON VALUE READ BY begin READ_INTEGER() AT RUN TIME: first(); • INPUT IS POSITIVE: THE PROGRAM PRINTS A 2 end; • OTHERWISE: PROGRAM PRINTS A 1 begin • THE ASSIGNMENT TO THE VARIABLE A IN FIRST() a := 2; REFERS EITHER if read_integer() > 0 second(); • TO GLOBAL VARIABLE DECLARED IN PROGRAM SCOPES OR else • TO THE LOCAL VARIABLE DECLARED INSIDE first(); SECOND() 20 write(a); end. CS307 : Principles of Programming Languages - (c) Paul Fodor (CS Stony Brook), Tony Mione (SUNY Korea) and Pearson SCOPE RULES EXAMPLE: STATIC VS. DYNAMIC • STATIC SCOPE RULES REQUIRE REFERENCE TO RESOLVE TO THE MOST RECENT, COMPILE-TIME BINDING • GLOBAL VARIABLE A • DYNAMIC SCOPE RULES REQUIRE CHOICE OF THE MOST RECENT, ACTIVE BINDING AT RUN TIME • MOST COMMON USE OF DYNAMIC SCOPE RULES MAY BE TO PROVIDE IMPLICIT PARAMETERS TO SUBROUTINES • THIS IS CONSIDERED BAD PROGRAMMING PRACTICE TODAY (EXCEPT IN FUNCTIONAL LANGUAGES) • ALTERNATIVE MECHANISMS EXIST • STATIC VARIABLES THAT CAN BE MODIFIED BY AUXILIARY ROUTINES • DEFAULT AND OPTIONAL PARAMETERS 21 CS307 : Principles of Programming Languages - (c) Paul Fodor (CS Stony Brook), Tony Mione (SUNY Korea) and Pearson SCOPE RULES EXAMPLE: STATIC VS. DYNAMIC • AT RUN TIME: CREATE A BINDING FOR A WHEN ENTER MAIN PROGRAM IS ENTERED • CREATE ANOTHER BINDING FOR A WHEN CODE ENTERS SECOND() • MOST RECENT, ACTIVE BINDING WHEN FIRST() IS EXECUTED • SO VARIABLE LOCAL TO SECOND() IS MODIFIED, NOT GLOBAL VARIABLE • BUT, WRITE() PRINTS GLOBAL VARIABLE
Recommended publications
  • Programming Languages
    Programming Languages Recitation Summer 2014 Recitation Leader • Joanna Gilberti • Email: [email protected] • Office: WWH, Room 328 • Web site: http://cims.nyu.edu/~jlg204/courses/PL/index.html Homework Submission Guidelines • Submit all homework to me via email (at [email protected] only) on the due date. • Email subject: “PL– homework #” (EXAMPLE: “PL – Homework 1”) • Use file naming convention on all attachments: “firstname_lastname_hw_#” (example: "joanna_gilberti_hw_1") • In the case multiple files are being submitted, package all files into a ZIP file, and name the ZIP file using the naming convention above. What’s Covered in Recitation • Homework Solutions • Questions on the homeworks • For additional questions on assignments, it is best to contact me via email. • I will hold office hours (time will be posted on the recitation Web site) • Run sample programs that demonstrate concepts covered in class Iterative Languages Scoping • Sample Languages • C: static-scoping • Perl: static and dynamic-scoping (use to be only dynamic scoping) • Both gcc (to run C programs), and perl (to run Perl programs) are installed on the cims servers • Must compile the C program with gcc, and then run the generated executable • Must include the path to the perl executable in the perl script Basic Scope Concepts in C • block scope (nested scope) • run scope_levels.c (sl) • ** block scope: set of statements enclosed in braces {}, and variables declared within a block has block scope and is active and accessible from its declaration to the end of the block
    [Show full text]
  • Chapter 5 Names, Bindings, and Scopes
    Chapter 5 Names, Bindings, and Scopes 5.1 Introduction 198 5.2 Names 199 5.3 Variables 200 5.4 The Concept of Binding 203 5.5 Scope 211 5.6 Scope and Lifetime 222 5.7 Referencing Environments 223 5.8 Named Constants 224 Summary • Review Questions • Problem Set • Programming Exercises 227 CMPS401 Class Notes (Chap05) Page 1 / 20 Dr. Kuo-pao Yang Chapter 5 Names, Bindings, and Scopes 5.1 Introduction 198 Imperative languages are abstractions of von Neumann architecture – Memory: stores both instructions and data – Processor: provides operations for modifying the contents of memory Variables are characterized by a collection of properties or attributes – The most important of which is type, a fundamental concept in programming languages – To design a type, must consider scope, lifetime, type checking, initialization, and type compatibility 5.2 Names 199 5.2.1 Design issues The following are the primary design issues for names: – Maximum length? – Are names case sensitive? – Are special words reserved words or keywords? 5.2.2 Name Forms A name is a string of characters used to identify some entity in a program. Length – If too short, they cannot be connotative – Language examples: . FORTRAN I: maximum 6 . COBOL: maximum 30 . C99: no limit but only the first 63 are significant; also, external names are limited to a maximum of 31 . C# and Java: no limit, and all characters are significant . C++: no limit, but implementers often impose a length limitation because they do not want the symbol table in which identifiers are stored during compilation to be too large and also to simplify the maintenance of that table.
    [Show full text]
  • Introduction to Programming in Lisp
    Introduction to Programming in Lisp Supplementary handout for 4th Year AI lectures · D W Murray · Hilary 1991 1 Background There are two widely used languages for AI, viz. Lisp and Prolog. The latter is the language for Logic Programming, but much of the remainder of the work is programmed in Lisp. Lisp is the general language for AI because it allows us to manipulate symbols and ideas in a commonsense manner. Lisp is an acronym for List Processing, a reference to the basic syntax of the language and aim of the language. The earliest list processing language was in fact IPL developed in the mid 1950’s by Simon, Newell and Shaw. Lisp itself was conceived by John McCarthy and students in the late 1950’s for use in the newly-named field of artificial intelligence. It caught on quickly in MIT’s AI Project, was implemented on the IBM 704 and by 1962 to spread through other AI groups. AI is still the largest application area for the language, but the removal of many of the flaws of early versions of the language have resulted in its gaining somewhat wider acceptance. One snag with Lisp is that although it started out as a very pure language based on mathematic logic, practical pressures mean that it has grown. There were many dialects which threaten the unity of the language, but recently there was a concerted effort to develop a more standard Lisp, viz. Common Lisp. Other Lisps you may hear of are FranzLisp, MacLisp, InterLisp, Cambridge Lisp, Le Lisp, ... Some good things about Lisp are: • Lisp is an early example of an interpreted language (though it can be compiled).
    [Show full text]
  • Scope in Fortran 90
    Scope in Fortran 90 The scope of objects (variables, named constants, subprograms) within a program is the portion of the program in which the object is visible (can be use and, if it is a variable, modified). It is important to understand the scope of objects not only so that we know where to define an object we wish to use, but also what portion of a program unit is effected when, for example, a variable is changed, and, what errors might occur when using identifiers declared in other program sections. Objects declared in a program unit (a main program section, module, or external subprogram) are visible throughout that program unit, including any internal subprograms it hosts. Such objects are said to be global. Objects are not visible between program units. This is illustrated in Figure 1. Figure 1: The figure shows three program units. Main program unit Main is a host to the internal function F1. The module program unit Mod is a host to internal function F2. The external subroutine Sub hosts internal function F3. Objects declared inside a program unit are global; they are visible anywhere in the program unit including in any internal subprograms that it hosts. Objects in one program unit are not visible in another program unit, for example variable X and function F3 are not visible to the module program unit Mod. Objects in the module Mod can be imported to the main program section via the USE statement, see later in this section. Data declared in an internal subprogram is only visible to that subprogram; i.e.
    [Show full text]
  • Programming Language Concepts/Binding and Scope
    Programming Language Concepts/Binding and Scope Programming Language Concepts/Binding and Scope Onur Tolga S¸ehito˘glu Bilgisayar M¨uhendisli˘gi 11 Mart 2008 Programming Language Concepts/Binding and Scope Outline 1 Binding 6 Declarations 2 Environment Definitions and Declarations 3 Block Structure Sequential Declarations Monolithic block structure Collateral Declarations Flat block structure Recursive declarations Nested block structure Recursive Collateral Declarations 4 Hiding Block Expressions 5 Static vs Dynamic Scope/Binding Block Commands Static binding Block Declarations Dynamic binding 7 Summary Programming Language Concepts/Binding and Scope Binding Binding Most important feature of high level languages: programmers able to give names to program entities (variable, constant, function, type, ...). These names are called identifiers. Programming Language Concepts/Binding and Scope Binding Binding Most important feature of high level languages: programmers able to give names to program entities (variable, constant, function, type, ...). These names are called identifiers. definition of an identifier ⇆ used position of an identifier. Formally: binding occurrence ⇆ applied occurrence. Programming Language Concepts/Binding and Scope Binding Binding Most important feature of high level languages: programmers able to give names to program entities (variable, constant, function, type, ...). These names are called identifiers. definition of an identifier ⇆ used position of an identifier. Formally: binding occurrence ⇆ applied occurrence. Identifiers are declared once, used n times. Programming Language Concepts/Binding and Scope Binding Binding Most important feature of high level languages: programmers able to give names to program entities (variable, constant, function, type, ...). These names are called identifiers. definition of an identifier ⇆ used position of an identifier. Formally: binding occurrence ⇆ applied occurrence. Identifiers are declared once, used n times.
    [Show full text]
  • Names, Scopes, and Bindings (Cont.)
    Chapter 3:: Names, Scopes, and Bindings (cont.) Programming Language Pragmatics Michael L. Scott Copyright © 2005 Elsevier Review • What is a regular expression ? • What is a context-free grammar ? • What is BNF ? • What is a derivation ? • What is a parse ? • What are terminals/non-terminals/start symbol ? • What is Kleene star and how is it denoted ? • What is binding ? Copyright © 2005 Elsevier Review • What is early/late binding with respect to OOP and Java in particular ? • What is scope ? • What is lifetime? • What is the “general” basic relationship between compile time/run time and efficiency/flexibility ? • What is the purpose of scope rules ? • What is central to recursion ? Copyright © 2005 Elsevier 1 Lifetime and Storage Management • Maintenance of stack is responsibility of calling sequence and subroutine prolog and epilog – space is saved by putting as much in the prolog and epilog as possible – time may be saved by • putting stuff in the caller instead or • combining what's known in both places (interprocedural optimization) Copyright © 2005 Elsevier Lifetime and Storage Management • Heap for dynamic allocation Copyright © 2005 Elsevier Scope Rules •A scope is a program section of maximal size in which no bindings change, or at least in which no re-declarations are permitted (see below) • In most languages with subroutines, we OPEN a new scope on subroutine entry: – create bindings for new local variables, – deactivate bindings for global variables that are re- declared (these variable are said to have a "hole" in their
    [Show full text]
  • Class 15: Implementing Scope in Function Calls
    Class 15: Implementing Scope in Function Calls SI 413 - Programming Languages and Implementation Dr. Daniel S. Roche United States Naval Academy Fall 2011 Roche (USNA) SI413 - Class 15 Fall 2011 1 / 10 Implementing Dynamic Scope For dynamic scope, we need a stack of bindings for every name. These are stored in a Central Reference Table. This primarily consists of a mapping from a name to a stack of values. The Central Reference Table may also contain a stack of sets, each containing identifiers that are in the current scope. This tells us which values to pop when we come to an end-of-scope. Roche (USNA) SI413 - Class 15 Fall 2011 2 / 10 Example: Central Reference Tables with Lambdas { new x := 0; new i := -1; new g := lambda z{ ret :=i;}; new f := lambda p{ new i :=x; i f (i>0){ ret :=p(0); } e l s e { x :=x + 1; i := 3; ret :=f(g); } }; w r i t e f( lambda y{ret := 0}); } What gets printed by this (dynamically-scoped) SPL program? Roche (USNA) SI413 - Class 15 Fall 2011 3 / 10 (dynamic scope, shallow binding) (dynamic scope, deep binding) (lexical scope) Example: Central Reference Tables with Lambdas The i in new g := lambda z{ w r i t e i;}; from the previous program could be: The i in scope when the function is actually called. The i in scope when g is passed as p to f The i in scope when g is defined Roche (USNA) SI413 - Class 15 Fall 2011 4 / 10 Example: Central Reference Tables with Lambdas The i in new g := lambda z{ w r i t e i;}; from the previous program could be: The i in scope when the function is actually called.
    [Show full text]
  • Java Programming 2 – Lecture #1 – [email protected]
    Java Programming 2 – Lecture #1 – [email protected] About the Java Programming Language Java is an object-oriented, high-level programming language. It is a platform-neutral language, with a ‘write once run anywhere’ philosophy. This is supported by a virtual machine architecture called the Java Virtual Machine (JVM). Java source programs are compiled to JVM bytecode class files, which are converted to native machine code on platform-specific JVM instances. .java source .class JVM executable code files Java bytecode files JVM machine code compiler runtime Java is currently one of the top programming languages, according to most popularity metrics.1 Since its introduction in the late 1990s, it has rapidly grown in importance due to its familiar programming syntax (C-like), good support for modularity, relatively safe features (e.g. garbage collection) and comprehensive library support. Our First Java Program It is traditional to write a ‘hello world’ program as a first step in a new language: /** * a first example program to print Hello world */ public class Hello { public static void main(String [] args) { System.out.println(“Hello world”); } } Contrast with Python Whereas Python programs are concise, Java programs appear verbose in comparison. Python has dynamic typing, but Java uses static typing. Python scripts are generally interpreted from source, whereas Java programs are compiled to bytecode then executed in a high-performance just-in-time native compiler. 1 E.g. see http://www.tiobe.com/index.php/content/paperinfo/tpci/index.html Supporting User Input in Simple Java Programs There are two ways to receive text-based user input in simple programs like our ‘hello world’ example.
    [Show full text]
  • Using the Java Bridge
    Using the Java Bridge In the worlds of Mac OS X, Yellow Box for Windows, and WebObjects programming, there are two languages in common use: Java and Objective-C. This document describes the Java bridge, a technology from Apple that makes communication between these two languages possible. The first section, ÒIntroduction,Ó gives a brief overview of the bridgeÕs capabilities. For a technical overview of the bridge, see ÒHow the Bridge WorksÓ (page 2). To learn how to expose your Objective-C code to Java, see ÒWrapping Objective-C FrameworksÓ (page 9). If you want to write Java code that references Objective-C classes, see ÒUsing Java-Wrapped Objective-C ClassesÓ (page 6). If you are writing Objective-C code that references Java classes, read ÒUsing Java from Objective-CÓ (page 5). Introduction The original OpenStep system developed by NeXT Software contained a number of object-oriented frameworks written in the Objective-C language. Most developers who used these frameworks wrote their code in Objective-C. In recent years, the number of developers writing Java code has increased dramatically. For the benefit of these programmers, Apple Computer has provided Java APIs for these frameworks: Foundation Kit, AppKit, WebObjects, and Enterprise Objects. They were made possible by using techniques described later in Introduction 1 Using the Java Bridge this document. You can use these same techniques to expose your own Objective-C frameworks to Java code. Java and Objective-C are both object-oriented languages, and they have enough similarities that communication between the two is possible. However, there are some differences between the two languages that you need to be aware of in order to use the bridge effectively.
    [Show full text]
  • Javascript Scope Lab Solution Review (In-Class) Remember That Javascript Has First-Class Functions
    C152 – Programming Language Paradigms Prof. Tom Austin, Fall 2014 JavaScript Scope Lab Solution Review (in-class) Remember that JavaScript has first-class functions. function makeAdder(x) { return function (y) { return x + y; } } var addOne = makeAdder(1); console.log(addOne(10)); Warm up exercise: Create a makeListOfAdders function. input: a list of numbers returns: a list of adders function makeListOfAdders(lst) { var arr = []; for (var i=0; i<lst.length; i++) { var n = lst[i]; arr[i] = function(x) { return x + n; } } return arr; } Prints: 121 var adders = 121 makeListOfAdders([1,3,99,21]); 121 adders.forEach(function(adder) { 121 console.log(adder(100)); }); function makeListOfAdders(lst) { var arr = []; for (var i=0; i<lst.length; i++) { arr[i]=function(x) {return x + lst[i];} } return arr; } Prints: var adders = NaN makeListOfAdders([1,3,99,21]); NaN adders.forEach(function(adder) { NaN console.log(adder(100)); NaN }); What is going on in this wacky language???!!! JavaScript does not have block scope. So while you see: for (var i=0; i<lst.length; i++) var n = lst[i]; the interpreter sees: var i, n; for (i=0; i<lst.length; i++) n = lst[i]; In JavaScript, this is known as variable hoisting. Faking block scope function makeListOfAdders(lst) { var i, arr = []; for (i=0; i<lst.length; i++) { (function() { Function creates var n = lst[i]; new scope arr[i] = function(x) {return x + n;} })(); } return arr; } A JavaScript constructor name = "Monty"; function Rabbit(name) { this.name = name; } var r = Rabbit("Python"); Forgot new console.log(r.name);
    [Show full text]
  • First-Class Functions
    Chapter 6 First-Class Functions We began Section 4 by observing the similarity between a with expression and a function definition applied immediately to a value. Specifically, we observed that {with {x 5} {+ x 3}} is essentially the same as f (x) = x + 3; f (5) Actually, that’s not quite right: in the math equation above, we give the function a name, f , whereas there is no identifier named f anywhere in the WAE program. We can, however, rewrite the mathematical formula- tion as f = λ(x).x + 3; f (5) which we can then rewrite as (λ(x)x + 3)(5) to get rid of the unnecessary name ( f ). That is, with effectively creates a new anonymous function and immediately applies it to a value. Because functions are useful in their own right, we may want to separate the act of function declaration or definition from invocation or application (indeed, we might want to apply the same function multiple times). That is what we will study now. 6.1 A Taxonomy of Functions The translation of with into mathematical notation exploits two features of functions: the ability to cre- ate anonymous functions, and the ability to define functions anywhere in the program (in this case, in the function position of an application). Not every programming language offers one or both of these capabili- ties. There is, therefore, a standard taxonomy that governs these different features, which we can use when discussing what kind of functions a language provides: first-order Functions are not values in the language. They can only be defined in a designated portion of the program, where they must be given names for use in the remainder of the program.
    [Show full text]
  • A History of Clojure
    A History of Clojure RICH HICKEY, Cognitect, Inc., USA Shepherd: Mira Mezini, Technische Universität Darmstadt, Germany Clojure was designed to be a general-purpose, practical functional language, suitable for use by professionals wherever its host language, e.g., Java, would be. Initially designed in 2005 and released in 2007, Clojure is a dialect of Lisp, but is not a direct descendant of any prior Lisp. It complements programming with pure functions of immutable data with concurrency-safe state management constructs that support writing correct multithreaded programs without the complexity of mutex locks. Clojure is intentionally hosted, in that it compiles to and runs on the runtime of another language, such as the JVM. This is more than an implementation strategy; numerous features ensure that programs written in Clojure can leverage and interoperate with the libraries of the host language directly and efficiently. In spite of combining two (at the time) rather unpopular ideas, functional programming and Lisp, Clojure has since seen adoption in industries as diverse as finance, climate science, retail, databases, analytics, publishing, healthcare, advertising and genomics, and by consultancies and startups worldwide, much to the career-altering surprise of its author. Most of the ideas in Clojure were not novel, but their combination puts Clojure in a unique spot in language design (functional, hosted, Lisp). This paper recounts the motivation behind the initial development of Clojure and the rationale for various design decisions and language constructs. It then covers its evolution subsequent to release and adoption. CCS Concepts: • Software and its engineering ! General programming languages; • Social and pro- fessional topics ! History of programming languages.
    [Show full text]