First-Class Functions • Reading: Appel 15.1-15.6 27 Apr 01

Total Page:16

File Type:pdf, Size:1020Kb

First-Class Functions • Reading: Appel 15.1-15.6 27 Apr 01 Administration CS 412 • Programming Assignment 6 write-up due in one week Introduction to Compilers – register allocation Andrew Myers –constant folding Cornell University – unreachable code elimination Lecture 35: First-class functions • Reading: Appel 15.1-15.6 27 Apr 01 Lecture 35 CS 412/413 Spring '01 -- Andrew Myers 2 Advanced Language Support First-class vs. Second-class • “advanced” language features so far: • Values are first-class if they can be used in objects all the usual ways • Next four lectures: more modern language – assigned to local variables features – passed as arguments to functions/methods – first-class functions – returned from functions –exceptions – created at run-time – parametric polymorphism • Iota: modules, functions are denoted by – dynamic typing and meta-object protocols expressions but are only usable in limited ways (uses, function call) Lecture 35 CS 412/413 Spring '01 -- Andrew Myers 3 Lecture 35 CS 412/413 Spring '01 -- Andrew Myers 4 First-class functions Function Types + • Many languages allow functions to be used •Iota-F0: Iota with function values that can be in a more first-class manner than in Iota passed as arguments (still not fully first-class) or Java: C, C++, ML, Modula-3, Pascal, • Need to declare type of argument; will use Scheme,... program notation function(T1, T2): T3 to denote the function type T ×T →T . – Passed as arguments to functions/methods 1 2 3 • Example: sorting with a user-specified ordering: – Nested within containing functions sort(a: array[int], (exc. C, C++) order: function(int, int):bool) { – Used as return values (exc. Modula-3, Pascal) … if (order(a[i], a[j])) { … } ... Lecture 35 CS 412/413 Spring '01 -- Andrew Myers 5 Lecture 35 CS 412/413 Spring '01 -- Andrew Myers 6 1 Passing a Function Value Objects subsume functions! leq(x: int, y: int): bool = x <= y interface comparer { geq(x: int, y:int): bool = x >= y compare(x: int, y:int): bool sort(a: array[int], } order: function(int, int):bool) … sort(a: array[int], cmp: comparer) { … if (cmp.compare(a[i], a[j])) { … } … sort(a1, leq) sort(a2, geq) class leq implements comparer { compare(x: int, y:int) = x <= y; • Allows abstraction over choice of } functions sort(a1, new leq); Lecture 35 CS 412/413 Spring '01 -- Andrew Myers 7 Lecture 35 CS 412/413 Spring '01 -- Andrew Myers 8 Type-checking functions Representing functions • Same rules as in Iota static semantics, but •For Iota-F0, a function may be represented function invoked in function call may be a as a pointer to its code (cheaper than an object) general expression • Old translation: E f(e1,…,en) = → ∈ A e : T × ... × T →T E E f : T1 × ... × Tn TR A 0 1 n R CALL(NAME( f ), e1 ,…, en ) i ∈ 1..n i ∈ 1..n A ei : Ti A ei : Ti • New: Ee (e ,…,e )= A f ( e ,..., e ) : T 0 1 n 1 n R A e0 ( e1,..., en ) : TR E E E CALL( e0 , e1 ,…, en ) • Subtyping on function types: usual Eid = NAME(id) contravariant/covariant conditions (if id is a global fcn) Lecture 35 CS 412/413 Spring '01 -- Andrew Myers 9 Lecture 35 CS 412/413 Spring '01 -- Andrew Myers 10 Nested Functions Iteration in Iota-F1 • Also useful for iterators, other user-defined control flow • In functional languages (Scheme, ML) and constructs interface set { members(f: function(o: object)) } Pascal, Modula-3, Iota-F1 • Nested function can access variables of the countAnimals(s: set) = ( containing lexical scope count: int = 0; loop_body(o: object) = ( plot_graph(f: function(x: float): float)= if (cast(o, Animal)) count ++; ( … y = f(x) … ) ) plot_quadratic(a,b,c: float) = ( s.members(loop_body); q(x: float): float = a*x*x+b*x+c; return count; plot_graph(q) ) • Nested functions may access, update free variables from ) containing scopes! Must change function representation nested function free variables Lecture 35 CS 412/413 Spring '01 -- Andrew Myers 11 Lecture 35 CS 412/413 Spring '01 -- Andrew Myers 12 2 A subtle program Lexical scope int f(n: int, • g(): int = x creates a new function value g1: function(): int, • Free variable (x) is bound to the variable g2: function(): int) = ( lexically visible at evaluation of function int x = n+10; expression int f(n: int, g(): int = x; g1: function(): int, if (n == 0) f(1, g, dummy) g2: function(): int) = ( call stack int x = n+10; else if (n==1) f(2, g1, g) call stack f(0,dummy,dummy) x=10 f(0,dummy,dummy) x=10 g(): int = x; else g1() + g2() + g() f(1, g, dummy) x=11 f(1,g,dummy) x=11 if (n == 0) f(1, g, dummy) else if (n==1) f(2, g1, g) ) f(2,g1,g) x=12 f(2, g1, g) x=12 else g1() + g2() + g() g1(), g2(), g() g1(), g2(), g() f(0,dummy,dummy) = ? ) Lecture 35 CS 412/413 Spring '01 -- Andrew Myers 13 Lecture 35 CS 412/413 Spring '01 -- Andrew Myers 14 Closures Closure • Problem: nested function (g) may need to • Closure -- A pointer to the code plus a static link to allow access to outer scope access variables arbitrarily high up on • Static link passed to function code as implicit stack argument • Before nested functions: function value was pointer to code (1 word) f activation record f(n: int, …) = { • With nested functions: function value is a x int x = n + 10; g g(): int = x; closure of code + environment for free other stack g closure … frames } variables code ptr (2 words) g activation record static link static link shared g Lecture 35 CS 412/413 Spring '01 -- Andrew Myers 15 Lecture 35 CS 412/413 Spring '01 -- Andrew Myers code 16 Supporting Closures Static Link Chains E e0(e1,…,en) = f() = (a: int; E implicit static link argument ESEQ(MOVE(t1, e0 ), g() = (b:int; f stack frame E E CALL(MEM(t1), MEM(t1+4), e1 ,…, en ) h() = ( a Sid(..a : T ..) : T = e= ...other function i i R c = a + b; stack frames... t1 = FP — k ; g stack frame id ) … b [t1] = NAME(id); t1 code addr static link to f [t1+4] = FP; static link ) … ...other function stack frames... • Can optimize direct calls ) h stack frame • Function variable takes 2 stack locations static link to g • What about variable accesses? Lecture 35 CS 412/413 Spring '01 -- Andrew Myers 17 Lecture 35 CS 412/413 Spring '01 -- Andrew Myers 18 3 Variable access code Progress Report • Local variable access √ Passed as arguments to unchanged f stack frame functions/methods • Free variable access: a √ Nested within containing functions as walk up n static links ...other function before indexing to stack frames... local variables g stack frame variable b —Used as return values static link to f • If no nested functions, functions are just ...other function stack frames... pointers to code; can be used as return values (C) h stack frame static link to g • Problem: interaction with nested fcns Lecture 35 CS 412/413 Spring '01 -- Andrew Myers 19 Lecture 35 CS 412/413 Spring '01 -- Andrew Myers 20 Iota-F2 (first-class functions) Dangling static link! •Augment Iota-F1 to allow the return ret addr make_counter( ): (function( ): int) = ( type of a function to be a function itself. // returns a counter function old FP int count; make_counter( ): (function( ): int) = ( count make_counter inc( ): int = ( count++; ) stack frame return inc; // returns a new counter function ) int count = 0; inc inc(): int = ( count++ ); return inc inc code ) make_counter()() + make_counter()() = ? c = make_counter(); c() + c() + c() = ? Lecture 35 CS 412/413 Spring '01 -- Andrew Myers 21 Lecture 35 CS 412/413 Spring '01 -- Andrew Myers 22 Heap allocation The GC side-effect ret addr stack make_counter( ): function( ): int = ( • Every function call creates an object that frame old fp // returns a counter function must be garbage collected eventually -- make_counter int count; activation inc( ): int = ( count++; ) increases rate of garbage generation record return inc; count ) • Activation records of all lexically enclosing functions are reachable from a closure via inc stack link chains inc code • Activation record makes a lot of garbage • Solution: heap-allocate the look reachable! make_counter activation record (at least count) • Activation record ≠ stack frame •Even local variable accesses indirected Lecture 35 CS 412/413 Spring '01 -- Andrew Myers 23 Lecture 35 CS 412/413 Spring '01 -- Andrew Myers 24 4 Escape analysis Example • Idea: local variable only needs to be stored on make_counter(start: int): function( ): int = ( // returns a counter function heap if it can escape and be accessed after this int count = start; function returns inc( ): int = ( c: int; count++; ) return inc; • Only happens if ) – variable is referenced from within some nested activation escaping variable function and stack frame stack frame record (heap) record (heap) – the nested function is turned into a closure: •returned, or start start ret addr count • passed to some function that might store it in a data ret addr start structure old fp old fp count (calls to nested functions not a problem) inc • This determination: escape analysis inc Lecture 35 CS 412/413 Spring '01 -- Andrew Myers 25 Lecture 35 CS 412/413 Spring '01 -- Andrew Myers 26 Benefits of escape analysis Summary • Variables that don’t escape are allocated • Looked at 3 languages progressively making functions more first-class on stack frame instead of heap: cheap to • No lexical nesting (F0, C) access – Fast but limited • If no escaping variables, no heap – Function = pointer to code allocation at all (common case) • Lexical nesting, no upward function values or storage in data structures (F1, Pascal, Modula-[123]): • Closures don’t pin down as much garbage – function value is closure (F , Scheme, ML): when created • Fully first-class: return values 2 – lots of heap-allocation, more indirection • One problem: precise escape analysis is a – Functions roughly as powerful as objects (sometimes more global analysis, expensive.
Recommended publications
  • Declare Function Inside a Function Python
    Declare Function Inside A Function Python Transisthmian and praetorian Wye never ensphere helter-skelter when Shawn lord his nightshade. Larboard Hal rumors her dizziesacapnia very so encouragingly actinally. that Colbert aurifies very inferentially. Kenyan Tad reframes her botts so irefully that Etienne Closures prove to it efficient way something we took few functions in our code. Hope you have any mutable object. Calling Functions from Other Files Problem Solving with Python. What embassy your website look like? Then you can declare any result of a million developers have been loaded? The coach who asked this gas has marked it as solved. We focus group functions together can a Python module see modules and it this way lead our. What are Lambda Functions and How to Use Them? It working so art the result variable is only accessible inside the function in. Variables inside python node, learn more detail, regardless of instances of a program demonstrates it. The python function inside another, which start here, and beginners start out. Get code examples like python define a function within a function instantly right anytime your google search results with the Grepper Chrome. The function by replacing it contains one function start here are discussed: how do not provide extremely cost efficient as their name? How to the page helpful for case it requires you can declare python data science. Each item from the python function has arbitrary length arguments must first, but are only the output is simply the function to. We declare their perfomance varies with the gathered arguments using a wrapped the arguments does the computed fahrenheit to declare function inside a function python? List of python can declare a function inside a million other functions we declare function inside a function python.
    [Show full text]
  • Lecture Notes on Types for Part II of the Computer Science Tripos
    Q Lecture Notes on Types for Part II of the Computer Science Tripos Prof. Andrew M. Pitts University of Cambridge Computer Laboratory c 2016 A. M. Pitts Contents Learning Guide i 1 Introduction 1 2 ML Polymorphism 6 2.1 Mini-ML type system . 6 2.2 Examples of type inference, by hand . 14 2.3 Principal type schemes . 16 2.4 A type inference algorithm . 18 3 Polymorphic Reference Types 25 3.1 The problem . 25 3.2 Restoring type soundness . 30 4 Polymorphic Lambda Calculus 33 4.1 From type schemes to polymorphic types . 33 4.2 The Polymorphic Lambda Calculus (PLC) type system . 37 4.3 PLC type inference . 42 4.4 Datatypes in PLC . 43 4.5 Existential types . 50 5 Dependent Types 53 5.1 Dependent functions . 53 5.2 Pure Type Systems . 57 5.3 System Fw .............................................. 63 6 Propositions as Types 67 6.1 Intuitionistic logics . 67 6.2 Curry-Howard correspondence . 69 6.3 Calculus of Constructions, lC ................................... 73 6.4 Inductive types . 76 7 Further Topics 81 References 84 Learning Guide These notes and slides are designed to accompany 12 lectures on type systems for Part II of the Cambridge University Computer Science Tripos. The course builds on the techniques intro- duced in the Part IB course on Semantics of Programming Languages for specifying type systems for programming languages and reasoning about their properties. The emphasis here is on type systems for functional languages and their connection to constructive logic. We pay par- ticular attention to the notion of parametric polymorphism (also known as generics), both because it has proven useful in practice and because its theory is quite subtle.
    [Show full text]
  • Open C++ Tutorial∗
    Open C++ Tutorial∗ Shigeru Chiba Institute of Information Science and Electronics University of Tsukuba [email protected] Copyright c 1998 by Shigeru Chiba. All Rights Reserved. 1 Introduction OpenC++ is an extensible language based on C++. The extended features of OpenC++ are specified by a meta-level program given at compile time. For dis- tinction, regular programs written in OpenC++ are called base-level programs. If no meta-level program is given, OpenC++ is identical to regular C++. The meta-level program extends OpenC++ through the interface called the OpenC++ MOP. The OpenC++ compiler consists of three stages: preprocessor, source-to-source translator from OpenC++ to C++, and the back-end C++ com- piler. The OpenC++ MOP is an interface to control the translator at the second stage. It allows to specify how an extended feature of OpenC++ is translated into regular C++ code. An extended feature of OpenC++ is supplied as an add-on software for the compiler. The add-on software consists of not only the meta-level program but also runtime support code. The runtime support code provides classes and functions used by the base-level program translated into C++. The base-level program in OpenC++ is first translated into C++ according to the meta-level program. Then it is linked with the runtime support code to be executable code. This flow is illustrated by Figure 1. The meta-level program is also written in OpenC++ since OpenC++ is a self- reflective language. It defines new metaobjects to control source-to-source transla- tion. The metaobjects are the meta-level representation of the base-level program and they perform the translation.
    [Show full text]
  • Let's Get Functional
    5 LET’S GET FUNCTIONAL I’ve mentioned several times that F# is a functional language, but as you’ve learned from previous chapters you can build rich applications in F# without using any functional techniques. Does that mean that F# isn’t really a functional language? No. F# is a general-purpose, multi paradigm language that allows you to program in the style most suited to your task. It is considered a functional-first lan- guage, meaning that its constructs encourage a functional style. In other words, when developing in F# you should favor functional approaches whenever possible and switch to other styles as appropriate. In this chapter, we’ll see what functional programming really is and how functions in F# differ from those in other languages. Once we’ve estab- lished that foundation, we’ll explore several data types commonly used with functional programming and take a brief side trip into lazy evaluation. The Book of F# © 2014 by Dave Fancher What Is Functional Programming? Functional programming takes a fundamentally different approach toward developing software than object-oriented programming. While object-oriented programming is primarily concerned with managing an ever-changing system state, functional programming emphasizes immutability and the application of deterministic functions. This difference drastically changes the way you build software, because in object-oriented programming you’re mostly concerned with defining classes (or structs), whereas in functional programming your focus is on defining functions with particular emphasis on their input and output. F# is an impure functional language where data is immutable by default, though you can still define mutable data or cause other side effects in your functions.
    [Show full text]
  • Explain Function Declaration Prototype and Definition
    Explain Function Declaration Prototype And Definition ligatedreprobated,Sidearm feminizes and but road-hoggish Weylin vengefully. phonemic Roderich nose-dived never reckons her acetones. his carat! Unfabled Dubitative Dewey and ill-equippedclangour, his Jerzy stringer See an example of passing control passes to function declaration and definition containing its prototype Once which is declared in definition precedes its definition of declaring a body of. Check out to explain basic elements must be explained below. They gain in this browser for types to carry out into parts of functions return statement of your pdf request that same things within your program? Arguments and definitions are explained below for this causes an operator. What it into two. In definition and declare a great; control is declared in this parameter names as declaring extern are explained in expressions and ms student at runtime error. Classes and definition was tested in a, and never executed but it will be called formal parameters are expanded at later. There are definitions to prototype definition tells the value method of an example are a function based on the warnings have had been declared. Please enter valid prototype definition looks a function definitions affects compilation. In this method is fixed words, but unlike references or rethrow errors or constants stand out its argument is only if more code by subclasses. How do is the variable of the three basic behavior of variable num to explain actual values of yours i desired. Also when a function num_multiplication function and definition example. By value of the definitions are explained in the nested function, the program passes to.
    [Show full text]
  • Run-Time Type Information and Incremental Loading in C++
    Run-time Type Information and Incremental Loading in C++ Murali Vemulapati Sriram Duvvuru Amar Gupta WP #3772 September 1993 PROFIT #93-11 Productivity From Information Technology "PROFIT" Research Initiative Sloan School of Management Massachusetts Institute of Technology Cambridge, MA 02139 USA (617)253-8584 Fax: (617)258-7579 Copyright Massachusetts Institute of Technology 1993. The research described herein has been supported (in whole or in part) by the Productivity From Information Technology (PROFIT) Research Initiative at MIT. This copy is for the exclusive use of PROFIT sponsor firms. Productivity From Information Technology (PROFIT) The Productivity From Information Technology (PROFIT) Initiative was established on October 23, 1992 by MIT President Charles Vest and Provost Mark Wrighton "to study the use of information technology in both the private and public sectors and to enhance productivity in areas ranging from finance to transportation, and from manufacturing to telecommunications." At the time of its inception, PROFIT took over the Composite Information Systems Laboratory and Handwritten Character Recognition Laboratory. These two laboratories are now involved in research re- lated to context mediation and imaging respectively. LABORATORY FOR ELEC RONICS A CENTERCFORENTER COORDINATION LABORATORY ) INFORMATION S RESEARCH RESE CH E53-310, MITAL"Room Cambridge, MA 02M142-1247 Tel: (617) 253-8584 E-Mail: [email protected] Run-time Type Information and Incremental Loading in C++ September 13, 1993 Abstract We present the design and implementation strategy for an integrated programming environment which facilitates specification, implementation and execution of persistent C++ programs. Our system is implemented in E, a persistent programming language based on C++. The environment provides type identity and type persistence, i.e., each user-defined class has a unique identity and persistence across compilations.
    [Show full text]
  • Fast Functional Simulation with a Dynamic Language
    Fast Functional Simulation with a Dynamic Language Craig S. Steele and JP Bonn Exogi LLC Las Vegas, Nevada, USA [email protected] Abstract—Simulation of large computational systems-on-a-chip runtime, rather than requiring mastery of a simulator-specific (SoCs) is increasing challenging as the number and complexity of domain-specific language (DSL) describing the binary-code components is scaled up. With the ubiquity of programmable translation task. components in computational SoCs, fast functional instruction- set simulation (ISS) is increasingly important. Much ISS has been done with straightforward functional models of a non-pipelined II. RELATED WORK fetch-decode-execute iteration written in a low-to-mid-level C- Interpretative instruction-set simulators (ISS) abound, with family static language, delivering mid-level efficiency. Some ISS various levels of detail in the processor model. The sim-fast programs, such as QEMU, perform dynamic binary translation simulator from SimpleScalar LLC is a well-known to allow software emulation to reach more usable speeds. This representative of a straightforward C-based fetch-decode- relatively complex methodology has not been widely adopted for execute iterative ISS interpreter, achieving more than 10 MIPS system modeling. for basic functional instruction-set-architecture (ISA) simulation [1]. This naïve approach is a software analog of a We demonstrate a fresh approach to ISS that achieves non-pipelined hardware processor implementation, simple but performance comparable to a fast dynamic binary translator by slow. exploiting recent advances in just-in-time (JIT) compilers for dynamic languages, such as JavaScript and Lua, together with a Many variations of binary translation for ISS exist, specific programming idiom inspired by pipelined processor translating instructions in the simulated ISA into code design.
    [Show full text]
  • Kodak Color Control Patches Kodak Gray
    Kodak Color Control Patches 0 - - _,...,...,. Blue Green Yellow Red White 3/Color . Black Kodak Gray Scale A 1 2 a 4 s -- - --- - -- - -- - -- -- - A Study of Compile-time Metaobject Protocol :J/1\'-(Jt.-S~..)(:$/;:t::;i':_;·I'i f-.· 7 •[:]f-. :::JJl.­ (:~9 ~~Jf'?E By Shigeru Chiba chiba~is.s.u-tokyo.ac.jp November 1996 A Dissertation Submitted to Department of Information Science Graduate School of Science The Un iversity of Tokyo In Partial Fulfillment of the Requirements For the Degree of Doctor of Science. Copyright @1996 by Shigeru Chiba. All Rights Reserved. - - - ---- - ~-- -- -~ - - - ii A Metaobject Protocol for Enabling Better C++ Libraries Shigeru Chiba Department of Information Science The University of Tokyo chiba~is.s.u-tokyo.ac.jp Copyrighl @ 1996 by Shi geru Chiba. All Ri ghts Reserved. iii iv Abstract C++ cannot be used to implement control/data abstractions as a library if their implementations require specialized code for each user code. This problem limits programmers to write libraries in two ways: it makes some kinds of useful abstractions that inherently require such facilities impossi­ ble to implement, and it makes other abstractions difficult to implement efficiently. T he OpenC++ MOP addresses this problem by providing li braries the ability to pre-process a program in a context-sensitive and non-local way. That is, libraries can instantiate specialized code depending on how the library is used and, if needed, substitute it for the original user code. The basic protocol structure of the Open C++ MOP is based on that of the CLOS MOP, but the Open C++ MOP runs metaobjects only at compile time.
    [Show full text]
  • Python Scope 3
    Class XII Computer Science : Python (Code: 083) Chapter: Functions Chapter : Functions Topics Covered: 1. Functions: scope Learning Outcomes: In this tutorial, we’ll learn: 1. What scopes are and how they work in Python 2. Why it’s important to know about Python scope 3. What is the LEGB rule 4. Using Python global statement and nonlocal statement Youtube Video Tutorial: 1. https://www.youtube.com/watch?v=07w3KkQqgi0 2. https://www.youtube.com/watch?v=R5uLNhRaGD0 3. https://www.youtube.com/watch?v=NdlWHlEgTn8 Python Scope Scope of a name (variables, functions etc) is the area of code where the name is created and can be used or accessed. A variable is only available from inside the region it is created. This is called scope. The scope of a name or variable depends on the place in our code where we create that variable. The Python scope concept is generally presented using a rule known as the LEGB rule. LEGB stand for Local, Enclosing, Global, and Built-in scopes. These are the names of Python scopes and also the sequence of steps that Python follows when accessing names in a program. Therefore in python there are 4 scopes 1. Local scope 2. Enclosing scope 3. Global scope 4. Built in scope 1 By Rajesh Singh ([email protected]) Class XII Computer Science : Python (Code: 083) Chapter: Functions Local Scope A variable created inside a function belongs to the local scope of that function, and can only be used inside that function. Example A variable created inside a function is available inside that function only: def myfunc(): x= 300 print(x) myfunc() print(x) # error, because x is created inside myfunc(), so it is available inside that function only Enclosing Scope (Function Inside a Function) A variable is available inside that function only in which it is created.
    [Show full text]
  • 1 Simply-Typed Lambda Calculus
    CS 4110 – Programming Languages and Logics Lecture #18: Simply Typed λ-calculus A type is a collection of computational entities that share some common property. For example, the type int represents all expressions that evaluate to an integer, and the type int ! int represents all functions from integers to integers. The Pascal subrange type [1..100] represents all integers between 1 and 100. You can see types as a static approximation of the dynamic behaviors of terms and programs. Type systems are a lightweight formal method for reasoning about behavior of a program. Uses of type systems include: naming and organizing useful concepts; providing information (to the compiler or programmer) about data manipulated by a program; and ensuring that the run-time behavior of programs meet certain criteria. In this lecture, we’ll consider a type system for the lambda calculus that ensures that values are used correctly; for example, that a program never tries to add an integer to a function. The resulting language (lambda calculus plus the type system) is called the simply-typed lambda calculus (STLC). 1 Simply-typed lambda calculus The syntax of the simply-typed lambda calculus is similar to that of untyped lambda calculus, with the exception of abstractions. Since abstractions define functions tht take an argument, in the simply-typed lambda calculus, we explicitly state what the type of the argument is. That is, in an abstraction λx : τ: e, the τ is the expected type of the argument. The syntax of the simply-typed lambda calculus is as follows. It includes integer literals n, addition e1 + e2, and the unit value ¹º.
    [Show full text]
  • 210 CHAPTER 7. NAMES and BINDING Chapter 8
    210 CHAPTER 7. NAMES AND BINDING Chapter 8 Expressions and Evaluation Overview This chapter introduces the concept of the programming environment and the role of expressions in a program. Programs are executed in an environment which is provided by the operating system or the translator. An editor, linker, file system, and compiler form the environment in which the programmer can enter and run programs. Interac- tive language systems, such as APL, FORTH, Prolog, and Smalltalk among others, are embedded in subsystems which replace the operating system in forming the program- development environment. The top-level control structure for these subsystems is the Read-Evaluate-Write cycle. The order of computation within a program is controlled in one of three basic ways: nesting, sequencing, or signaling other processes through the shared environment or streams which are managed by the operating system. Within a program, an expression is a nest of function calls or operators that returns a value. Binary operators written between their arguments are used in infix syntax. Unary and binary operators written before a single argument or a pair of arguments are used in prefix syntax. In postfix syntax, operators (unary or binary) follow their arguments. Parse trees can be developed from expressions that include infix, prefix and postfix operators. Rules for precedence, associativity, and parenthesization determine which operands belong to which operators. The rules that define order of evaluation for elements of a function call are as follows: • Inside-out: Evaluate every argument before beginning to evaluate the function. 211 212 CHAPTER 8. EXPRESSIONS AND EVALUATION • Outside-in: Start evaluating the function body.
    [Show full text]
  • Query Rewriting Using Views in a Typed Mediator
    Язык СИНТЕЗ как ядро канонической информационной модели Л. А. Калиниченко ([email protected]) C. А. Ступников ([email protected]) Lecture outline Objectives of the language Frame language: semi-structured capabilities Type system of SYNTHESIS Classes and metaclasses Assertions Processes, workflows Formulae facilities of the language 2 History of the language . Preliminary draft version published in 1991 . First version published in 1993 . English version prepared in 1995 and extended in 1997 . Current version in English published in 2007 3 The SYNTHESIS is a multipurpose language The language is oriented on the following basic kinds of application: . serving as a kernel of the canonical information model; . providing facilities for unifying representation of heterogeneous information models of different kinds (of data, services, processes, ontologies); . providing sufficient modeling facilities for formalized definitions of mediators for various subject domains; . supporting mediation-based design of information systems; . providing modeling facilities for mediator and resource specifications for the mediation architecture; . serving for semantic reconciliation of the mediator and resource specifications to form compositions of resources refining mediator specifications; . serving as an interface for users during problem formulation and solving in various applications 4 Mediation orientation . Two different approaches to the problem of integrated representation of multiple information resources for an IS are distinguished: 1. moving from resources to problems (resource driven approach) 2. moving from an application to resources (application driven approach) The SYNTHESIS language is oriented on support of application-driven approach for mediation-based IS development. The mediator's layer is introduced to provide the users with the metainformation uniformly characterizing subject definitions in the canonical information model – providing application domain conceptual schema .
    [Show full text]