Functional Perl: Programming with Recursion Schemes in Python

Total Page:16

File Type:pdf, Size:1020Kb

Functional Perl: Programming with Recursion Schemes in Python Functional Perl: Programming with Recursion Schemes in Python Robert J. Simmons Nels E. Beckman Dr. Tom Murphy VII, Ph.D. Carnegie Mellon University The tom7.org foundation frjsimmon,[email protected] [email protected] Abstract Algorithms that are fundamentally expressions of structural in- tm1 + x1 tm2 + x2 x1 + x2 = x3 duction over a polynomial data type are famously awkward to tm1 + tm2 + x3 int(x) + x implement in object-oriented programming languages, leading to Using the pattern matching syntax present in the ML family of three-day-bucket hacks like the “Visitor Pattern.” We show that the languages, the implementation of this big-step evaluation semantics exception-handling mechanism present in most object-oriented lan- is similarly straightforward: guages already suffices. Conventional wisdom dictates that exceptions are in essence fun eval tm = about the non-local propagation of errors. Upon close scrutiny, we case tm of find the contrary: exceptions are fundamentally about unchecked Int x => x depth-1 structural pattern matching. | Plus (tm1, tm2) => eval tm1 + eval tm2 We give examples of this programming idiom in Python, Perl, and Java. JavaScript requires a language extension, which we build We can also similarly implement a small step semantics for this and deploy. We then show how two styles by which this style may language as defined by the following rules: be re-integrated into programming languages in the ML family. We conclude by suggesting design changes that would facilitate the use int(x) value of this idiom in other languages. 0 0 tm1 7! tm1 tm1 value tm2 7! tm2 Categories and Subject Descriptors D.2.3 [Coding Tools and tm + tm 7! tm0 + tm tm + tm0 7! tm + tm0 Techniques]: Standards 1 2 1 2 1 2 1 2 x1 + x2 = x3 General Terms Algorithms, Design, Languages, Standardization int(x1) + int(x2) 7! int(x3) Keywords pattern matching, recursion schemes, structural induc- The ML implementation is a straightforward implementation tion, python, perl, java, javascript, types of these inference rules, with the exception of the need to define an additional cast function that we call to get the value of the 1. Introduction enclosed integers once we know the terms to be a values.1 Pattern matching is a convenient way of representing polynomial exception Stuck datatypes, which can be informally thought of as a generalization of tree-like data. An extremely simple example is an abstract syntax fun value tm = for a language with integers and addition: case tm of datatype tm = Int x => true Int of int | _ => false | Plus of tm * tm fun cast tm = The big-step evaluation semantics for this language is quite straight- case tm of forward: Int x => x | _ => raise Stuck Copyright c 2010 by Robert J. Simmons, Nels E. Beckman, and Tom Murphy VII. Permission is hereby granted, free of charge, to any person obtaining a copy of this fun step tm = software and associated documentation files (the ”Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, case tm of publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons Int x => raise Stuck to whom the Software is furnished to do so, subject to the following conditions: | Plus(tm1, tm2) => The above copyright notice and this permission notice shall be included in all copies if value tm1 or substantial portions of the Software. THE SOFTWARE IS PROVIDED ”AS IS”, WITHOUT WARRANTY OF ANY then if value tm2 KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WAR- then Int(cast tm1 + cast tm2) RANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE else Plus(tm, step tm2) AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPY- else Plus(step tm1, tm2) RIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LI- ABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, 1 ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR In a language without static typing and with distinct varieties of values, THE USE OR OTHER DEALINGS IN THE SOFTWARE. these casts can, of course, fail if we get the wrong variety of value. interface tm class tm: { public <T> T accept(Visitor<T> visitor); } pass class Int implements tm { class Int(tm): int x; def __init__(self, x): public Int(int x) { this.x = x; } self.x = x public <T> T accept(Visitor<T> v) class Plus(tm): { return v.visit(this); } def __init__(self, e1, e2): } self.e1 = e1 class Plus implements tm { self.e2 = e2 tm e1; tm e2; def eval(tm): public Plus(tm e1, tm e2) { try: raise tm this.e1 = e1; except Int: return tm.x this.e2 = e2; except Plus: return eval(tm.e1) + eval(tm.e2) } public <T> T accept(Visitor<T> v) def value(tm): { return v.visit(this); } try: raise tm } except Int: return True except: return False interface Visitor<T> { public T visit(Plus p); def step(tm): public T visit(Int i); try: raise tm } except Plus: if(not value(tm.e1)): public class VisitorExample { return Plus(step(tm.e1), tm.e2) static int eval(tm tm) { elif(not value(tm.e2)): return tm.accept(new Visitor<Integer>(){ return Plus(tm.e1, step(tm.e2)) public Integer visit(Int i) { return i.x; } else: return Int(tm.e1.x + tm.e2.x) public Integer visit(Plus p) { return p.e1.accept(this) ex_1 = Plus(Plus(Plus(Int(1),Int(2)), + p.e2.accept(this); Int(3)),Int(4)) } print ("Evaluating: Plus(Plus(Plus(1,2),3),4) - " }); + str(eval(ex_1))) } print ("Stepping x3: Plus(Plus(Plus(1,2),3),4) - " + str(step(step(step(ex_1))).x)) public static void main(String[] args) { tm ex_1 = Figure 2. Python pattern matching case study. new Plus(new Plus(new Plus(new Int(1), new Int(2)), new Int(3)), new Int(4)); mechanism, which Java also incorporates, is fundamentally about System.out.println unchecked depth-1 structural pattern matching, we can seek to use ("Evaluating: Plus(Plus(Plus(1,2),3),4) - " exception handling to provide a similar sort of depth-1 structural + eval(ex_1)); pattern matching to the Java language and other object-oriented } programming languages. The rest of the paper explores this pos- } sibility. Figure 1. Case study implemented with the Visitor Pattern in Java. 2. Discovery and implementation in Python Imagine we have the abstract syntax of our example encoded in While there is a somewhat more pleasant way to implement the Python in the standard way, as a class hierarchy where subclasses Step function using nested pattern matching, we will only consider Int and Plus extend the basic abstract syntax class tm. the “shallow” pattern matching we see here in this paper. class tm: 1.1 Object-Oriented languages and the Visitor Pattern pass class Int(tm): While ML-family languages suggest describing different types of def __init__(self, x) syntax as different branches of a subtype, most object oriented self.x = x languages suggest describing different types of syntax as different class Plus(tm): objects that either implement the same interface or extend the same def __init__(self, e1, e2) subclass. The traditionally understood way of performing elegant self.e1 = e1 recursion over these structures is known as the Visitor Pattern; the self.e2 = e2 implementation of big-step evaluation using the Visitor Pattern can be seen in Figure 1. The big-step evaluation semantics of this language could be The Visitor Pattern, whatever its merits may be, is certainly written by explicitly using isinstance tests, but the repeated use quite different in character from the depth-1 pattern matching used of elif isinstance(tm, ...) is bulky and unsatisfying, which in our ML example. However, because the exception handling only becomes more true when the code has many, many branches: def eval(tm): class tm extends RuntimeException {} if isinstance(tm, Int): final class Int extends tm { return tm.x final Integer x; elif isinstance(tm, Plus): Int(Integer x) { this.x = x; } return eval(tm.e1) + eval(tm.e2) } else: raise RuntimeError final class Plus extends tm { final tm e1; Note the final line of the above code, which raises a runtime final tm e2; error if the evaluated term is neither an Int nor a Plus. This is Plus(tm e1, tm e2) { important in case we extend the abstract syntax tree with more this.e1 = e1; branches; we want something equivalent to the “nonexhaustive this.e2 = e2; match exception” in an ML-family language. } } 2.1 Utilizing the exception handling mechanism public class PatternMatch { The first key observation for introducing our idiom is the fact that every single object in Python can be treated as an exception static Integer eval(tm tm) { and thrown; the language designers suggest that exceptions derive try{throw tm;} from the Exception class, but there is no enforcement of this catch(Int i) { return i.x; } mechanism. The second key observation is that the branches of catch(Plus p) an exception handling call can check the object’s class tag when { return eval(p.e1) + eval(p.e2); } deciding which branch of the exception handling to consider. The } motivation is to allow, say, a divide-by-zero error or a user-input error to be both caught at the same place but handled in different static Boolean value(tm tm) { ways; we can use it, however, to do exactly the isinstance test try{throw tm;} from before in a more concise, pleasing notation: catch(Int i) { return true; } catch(Plus p) { return false; } def eval(tm): } try: raise tm except Int: return tm.x static tm step(tm tm) { except Plus: return eval(tm.e1) + eval(tm.e2) try{throw tm;} catch(Plus p) { Furthermore, this form of evaluation introduces a natural notion if( !value(p.e1) ) of a nonexhaustive match exception: if we add new kinds of terms return new Plus(step(p.e1), p.e2); (say, a multiplication) and don’t handle them in the eval function, else if( !value(p.e2) ) the very abstract syntax tree node that we did not handle will be return new Plus(p.e1, step(p.e2)); thrown as an exception: an error that potentially contains much else more helpful information than an ML Match exception! return new Int ( ((Int)p.e1).x + ((Int)p.e2).x ); 2.2 Adaptation in Java } } The relatively-more-strongly-typed language Java also allows for the expression of our idiom by simply allowing every term to ex- public static void main(String[] args) { tend the class RuntimeException.
Recommended publications
  • X10 Language Specification
    X10 Language Specification Version 2.6.2 Vijay Saraswat, Bard Bloom, Igor Peshansky, Olivier Tardieu, and David Grove Please send comments to [email protected] January 4, 2019 This report provides a description of the programming language X10. X10 is a class- based object-oriented programming language designed for high-performance, high- productivity computing on high-end computers supporting ≈ 105 hardware threads and ≈ 1015 operations per second. X10 is based on state-of-the-art object-oriented programming languages and deviates from them only as necessary to support its design goals. The language is intended to have a simple and clear semantics and be readily accessible to mainstream OO pro- grammers. It is intended to support a wide variety of concurrent programming idioms. The X10 design team consists of David Grove, Ben Herta, Louis Mandel, Josh Milthorpe, Vijay Saraswat, Avraham Shinnar, Mikio Takeuchi, Olivier Tardieu. Past members include Shivali Agarwal, Bowen Alpern, David Bacon, Raj Barik, Ganesh Bikshandi, Bob Blainey, Bard Bloom, Philippe Charles, Perry Cheng, David Cun- ningham, Christopher Donawa, Julian Dolby, Kemal Ebcioglu,˘ Stephen Fink, Robert Fuhrer, Patrick Gallop, Christian Grothoff, Hiroshi Horii, Kiyokuni Kawachiya, Al- lan Kielstra, Sreedhar Kodali, Sriram Krishnamoorthy, Yan Li, Bruce Lucas, Yuki Makino, Nathaniel Nystrom, Igor Peshansky, Vivek Sarkar, Armando Solar-Lezama, S. Alexander Spoon, Toshio Suganuma, Sayantan Sur, Toyotaro Suzumura, Christoph von Praun, Leena Unnikrishnan, Pradeep Varma, Krishna Nandivada Venkata, Jan Vitek, Hai Chuan Wang, Tong Wen, Salikh Zakirov, and Yoav Zibin. For extended discussions and support we would like to thank: Gheorghe Almasi, Robert Blackmore, Rob O’Callahan, Calin Cascaval, Norman Cohen, Elmootaz El- nozahy, John Field, Kevin Gildea, Sara Salem Hamouda, Michihiro Horie, Arun Iyen- gar, Chulho Kim, Orren Krieger, Doug Lea, John McCalpin, Paul McKenney, Hiroki Murata, Andrew Myers, Filip Pizlo, Ram Rajamony, R.
    [Show full text]
  • Cygwin User's Guide
    Cygwin User’s Guide Cygwin User’s Guide ii Copyright © Cygwin authors Permission is granted to make and distribute verbatim copies of this documentation provided the copyright notice and this per- mission notice are preserved on all copies. Permission is granted to copy and distribute modified versions of this documentation under the conditions for verbatim copying, provided that the entire resulting derived work is distributed under the terms of a permission notice identical to this one. Permission is granted to copy and distribute translations of this documentation into another language, under the above conditions for modified versions, except that this permission notice may be stated in a translation approved by the Free Software Foundation. Cygwin User’s Guide iii Contents 1 Cygwin Overview 1 1.1 What is it? . .1 1.2 Quick Start Guide for those more experienced with Windows . .1 1.3 Quick Start Guide for those more experienced with UNIX . .1 1.4 Are the Cygwin tools free software? . .2 1.5 A brief history of the Cygwin project . .2 1.6 Highlights of Cygwin Functionality . .3 1.6.1 Introduction . .3 1.6.2 Permissions and Security . .3 1.6.3 File Access . .3 1.6.4 Text Mode vs. Binary Mode . .4 1.6.5 ANSI C Library . .4 1.6.6 Process Creation . .5 1.6.6.1 Problems with process creation . .5 1.6.7 Signals . .6 1.6.8 Sockets . .6 1.6.9 Select . .7 1.7 What’s new and what changed in Cygwin . .7 1.7.1 What’s new and what changed in 3.2 .
    [Show full text]
  • Automating Your Sync Testing
    APPLICATION NOTE By automating system verification and conformance testing to ITU-T synchronization standards, you’ll save on time and resources, and avoid potential test execution errors. This application note describes how you can use the Paragon-X’s Script Recorder to easily record Tcl, PERL and Python commands that can be integrated into your own test scripts for fast and efficient automated testing. AUTOMATING YOUR SYNC TESTING calnexsol.com Easily automate synchronization testing using the Paragon-X Fast and easy automation by Supports the key test languages Pre-prepared G.8262 Conformance recording GUI key presses Tcl, PERL and Python Scripts reduces test execution errors <Tcl> <PERL> <python> If you perform System Verification language you want to record i.e. Tcl, PERL SyncE CONFORMANCE TEST and Conformance Testing to ITU-T or Python, then select Start. synchronization standards on a regular Calnex provides Conformance Test Scripts basis, you’ll know that manual operation to ITU-T G.8262 for SyncE conformance of these tests can be time consuming, testing using the Paragon-X. These tedious and prone to operator error — as test scripts can also be easily tailored well as tying up much needed resources. and edited to meet your exact test Automation is the answer but very often requirements. This provides an easy means a lack of time and resource means it of getting your test automation up and remains on the ‘To do’ list. Now, with running and providing a repeatable means Calnex’s new Script Recorder feature, you of proving performance, primarily for ITU-T can get your automation up and running standards conformance.
    [Show full text]
  • Building Performance Measurement Tools for the MINIX 3 Operating System
    Building Performance Measurement Tools for the MINIX 3 Operating System Rogier Meurs August 2006 Contents 1 INTRODUCTION 1 1.1 Measuring Performance 1 1.2 MINIX 3 2 2 STATISTICAL PROFILING 3 2.1 Introduction 3 2.2 In Search of a Timer 3 2.2.1 i8259 Timers 3 2.2.2 CMOS Real-Time Clock 3 2.3 High-level Description 4 2.4 Work Done in User-Space 5 2.4.1 The SPROFILE System Call 5 2.5 Work Done in Kernel-Space 5 2.5.1 The SPROF Kernel Call 5 2.5.2 Profiling using the CMOS Timer Interrupt 6 2.6 Work Done at the Application Level 7 2.6.1 Control Tool: profile 7 2.6.2 Analyzing Tool: sprofalyze.pl 7 2.7 What Can and What Cannot be Profiled 8 2.8 Profiling Results 8 2.8.1 High Scoring IPC Functions 8 2.8.2 Interrupt Delay 9 2.8.3 Profiling Runs on Simulator and Other CPU Models 12 2.9 Side-effect of Using the CMOS Clock 12 3 CALL PROFILING 13 3.1 Introduction 13 3.1.1 Compiler-supported Call Profiling 13 3.1.2 Call Paths, Call and Cycle Attribution 13 3.2 High-level Description 14 3.3 Work Done in User-Space 15 3.3.1 The CPROFILE System Call 15 3.4 Work Done in Kernel-Space 16 3.4.1 The PROFBUF and CPROF Kernel Calls 16 3.5 Work Done in Libraries 17 3.5.1 Profiling Using Library Functions 17 3.5.2 The Procentry Library Function 17 3.5.3 The Procexit Library Function 20 3.5.4 The Call Path String 22 3.5.5 Testing Overhead Elimination 23 3.6 Profiling Kernel-Space/User-Space Processes 24 3.6.1 Differences in Announcing and Table Sizes 24 3.6.2 Kernel-Space Issue: Reentrancy 26 3.6.3 Kernel-Space Issue: The Call Path 26 3.7 Work Done at the Application
    [Show full text]
  • Exploring Languages with Interpreters and Functional Programming Chapter 22
    Exploring Languages with Interpreters and Functional Programming Chapter 22 H. Conrad Cunningham 5 November 2018 Contents 22 Overloading and Type Classes 2 22.1 Chapter Introduction . .2 22.2 Polymorphism in Haskell . .2 22.3 Why Overloading? . .2 22.4 Defining an Equality Class and Its Instances . .4 22.5 Type Class Laws . .5 22.6 Another Example Class Visible ..................5 22.7 Class Extension (Inheritance) . .6 22.8 Multiple Constraints . .7 22.9 Built-In Haskell Classes . .8 22.10Comparison to Other Languages . .8 22.11What Next? . .9 22.12Exercises . 10 22.13Acknowledgements . 10 22.14References . 11 22.15Terms and Concepts . 11 Copyright (C) 2017, 2018, H. Conrad Cunningham Professor of Computer and Information Science University of Mississippi 211 Weir Hall P.O. Box 1848 University, MS 38677 (662) 915-5358 Browser Advisory: The HTML version of this textbook requires use of a browser that supports the display of MathML. A good choice as of November 2018 is a recent version of Firefox from Mozilla. 1 22 Overloading and Type Classes 22.1 Chapter Introduction Chapter 5 introduced the concept of overloading. Chapters 13 and 21 introduced the related concepts of type classes and instances. The goal of this chapter and the next chapter is to explore these concepts in more detail. The concept of type class was introduced into Haskell to handle the problem of comparisons, but it has had a broader and more profound impact upon the development of the language than its original purpose. This Haskell feature has also had a significant impact upon the design of subsequent languages (e.g.
    [Show full text]
  • Teach Yourself Perl 5 in 21 Days
    Teach Yourself Perl 5 in 21 days David Till Table of Contents: Introduction ● Who Should Read This Book? ● Special Features of This Book ● Programming Examples ● End-of-Day Q& A and Workshop ● Conventions Used in This Book ● What You'll Learn in 21 Days Week 1 Week at a Glance ● Where You're Going Day 1 Getting Started ● What Is Perl? ● How Do I Find Perl? ❍ Where Do I Get Perl? ❍ Other Places to Get Perl ● A Sample Perl Program ● Running a Perl Program ❍ If Something Goes Wrong ● The First Line of Your Perl Program: How Comments Work ❍ Comments ● Line 2: Statements, Tokens, and <STDIN> ❍ Statements and Tokens ❍ Tokens and White Space ❍ What the Tokens Do: Reading from Standard Input ● Line 3: Writing to Standard Output ❍ Function Invocations and Arguments ● Error Messages ● Interpretive Languages Versus Compiled Languages ● Summary ● Q&A ● Workshop ❍ Quiz ❍ Exercises Day 2 Basic Operators and Control Flow ● Storing in Scalar Variables Assignment ❍ The Definition of a Scalar Variable ❍ Scalar Variable Syntax ❍ Assigning a Value to a Scalar Variable ● Performing Arithmetic ❍ Example of Miles-to-Kilometers Conversion ❍ The chop Library Function ● Expressions ❍ Assignments and Expressions ● Other Perl Operators ● Introduction to Conditional Statements ● The if Statement ❍ The Conditional Expression ❍ The Statement Block ❍ Testing for Equality Using == ❍ Other Comparison Operators ● Two-Way Branching Using if and else ● Multi-Way Branching Using elsif ● Writing Loops Using the while Statement ● Nesting Conditional Statements ● Looping Using
    [Show full text]
  • Difference Between Perl and Python Key Difference
    Difference Between Perl and Python www.differencebetween.com Key Difference - Perl vs Python A computer program provides instructions for a computer to perform tasks. A set of instructions is known as a computer program. A computer program is developed using a programming language. High-level languages are understandable by programmers but not understandable by the computer. Therefore, those programs are converted to machine-understandable format. Perl and Python are two high-level programming languages. Perl has features such as built-in regular expressions, file scanning and report generation. Python provides support for common programming methodologies such as data structures, algorithms etc. The key difference between Perl and Python is that Perl emphasizes support for common application-oriented tasks while Python emphasizes support for common programming methodologies. What is Perl? Perl is general purpose high-level programing language. It was designed by Larry Wall. Perl stands for Practical Extraction and Reporting Language. It is open source and is useful for text manipulation. Perl runs on various platforms such as Windows, Mac, Linux etc. It is a multi-paradigm language that supports mainly procedural programming and object-oriented programming. Procedure Programming helps to divide the program into functions. Object Oriented programming helps to model a software or a program using objects. Perl is an interpreted language. Therefore, each line is read one after the other by the interpreter. High-level language programs are understandable by the programmer, but they are not understandable by the machine. Therefore, the instructions should be converted into the machine-understandable format. Programming languages such as C and C++ converts the source code to machine language using a compiler.
    [Show full text]
  • On the Interaction of Object-Oriented Design Patterns and Programming
    On the Interaction of Object-Oriented Design Patterns and Programming Languages Gerald Baumgartner∗ Konstantin L¨aufer∗∗ Vincent F. Russo∗∗∗ ∗ Department of Computer and Information Science The Ohio State University 395 Dreese Lab., 2015 Neil Ave. Columbus, OH 43210–1277, USA [email protected] ∗∗ Department of Mathematical and Computer Sciences Loyola University Chicago 6525 N. Sheridan Rd. Chicago, IL 60626, USA [email protected] ∗∗∗ Lycos, Inc. 400–2 Totten Pond Rd. Waltham, MA 02154, USA [email protected] February 29, 1996 Abstract Design patterns are distilled from many real systems to catalog common programming practice. However, some object-oriented design patterns are distorted or overly complicated because of the lack of supporting programming language constructs or mechanisms. For this paper, we have analyzed several published design patterns looking for idiomatic ways of working around constraints of the implemen- tation language. From this analysis, we lay a groundwork of general-purpose language constructs and mechanisms that, if provided by a statically typed, object-oriented language, would better support the arXiv:1905.13674v1 [cs.PL] 31 May 2019 implementation of design patterns and, transitively, benefit the construction of many real systems. In particular, our catalog of language constructs includes subtyping separate from inheritance, lexically scoped closure objects independent of classes, and multimethod dispatch. The proposed constructs and mechanisms are not radically new, but rather are adopted from a variety of languages and programming language research and combined in a new, orthogonal manner. We argue that by describing design pat- terns in terms of the proposed constructs and mechanisms, pattern descriptions become simpler and, therefore, accessible to a larger number of language communities.
    [Show full text]
  • An Analysis of the Dynamic Behavior of Javascript Programs
    An Analysis of the Dynamic Behavior of JavaScript Programs Gregor Richards Sylvain Lebresne Brian Burg Jan Vitek S3 Lab, Department of Computer Science, Purdue University, West Lafayette, IN fgkrichar,slebresn,bburg,[email protected] Abstract becoming a general purpose computing platform with office appli- The JavaScript programming language is widely used for web cations, browsers and development environments [15] being devel- programming and, increasingly, for general purpose computing. oped in JavaScript. It has been dubbed the “assembly language” of the Internet and is targeted by code generators from the likes As such, improving the correctness, security and performance of 2;3 JavaScript applications has been the driving force for research in of Java and Scheme [20]. In response to this success, JavaScript type systems, static analysis and compiler techniques for this lan- has started to garner academic attention and respect. Researchers guage. Many of these techniques aim to reign in some of the most have focused on three main problems: security, correctness and dynamic features of the language, yet little seems to be known performance. Security is arguably JavaScript’s most pressing prob- about how programmers actually utilize the language or these fea- lem: a number of attacks have been discovered that exploit the lan- tures. In this paper we perform an empirical study of the dynamic guage’s dynamism (mostly the ability to access and modify shared behavior of a corpus of widely-used JavaScript programs, and an- objects and to inject code via eval). Researchers have proposed ap- alyze how and why the dynamic features are used.
    [Show full text]
  • PHP: Constructs and Variables Introduction This Document Describes: 1
    PHP: Constructs and Variables Introduction This document describes: 1. the syntax and types of variables, 2. PHP control structures (i.e., conditionals and loops), 3. mixed-mode processing, 4. how to use one script from within another, 5. how to define and use functions, 6. global variables in PHP, 7. special cases for variable types, 8. variable variables, 9. global variables unique to PHP, 10. constants in PHP, 11. arrays (indexed and associative), Brief overview of variables The syntax for PHP variables is similar to C and most other programming languages. There are three primary differences: 1. Variable names must be preceded by a dollar sign ($). 2. Variables do not need to be declared before being used. 3. Variables are dynamically typed, so you do not need to specify the type (e.g., int, float, etc.). Here are the fundamental variable types, which will be covered in more detail later in this document: • Numeric 31 o integer. Integers (±2 ); values outside this range are converted to floating-point. o float. Floating-point numbers. o boolean. true or false; PHP internally resolves these to 1 (one) and 0 (zero) respectively. Also as in C, 0 (zero) is false and anything else is true. • string. String of characters. • array. An array of values, possibly other arrays. Arrays can be indexed or associative (i.e., a hash map). • object. Similar to a class in C++ or Java. (NOTE: Object-oriented PHP programming will not be covered in this course.) • resource. A handle to something that is not PHP data (e.g., image data, database query result).
    [Show full text]
  • Thinking in C++ Volume 2 Annotated Solution Guide, Available for a Small Fee From
    1 z 516 Note: This document requires the installation of the fonts Georgia, Verdana and Andale Mono (code font) for proper viewing. These can be found at: http://sourceforge.net/project/showfiles.php?group_id=34153&release_id=105355 Revision 19—(August 23, 2003) Finished Chapter 11, which is now going through review and copyediting. Modified a number of examples throughout the book so that they will compile with Linux g++ (basically fixing case- sensitive naming issues). Revision 18—(August 2, 2003) Chapter 5 is complete. Chapter 11 is updated and is near completion. Updated the front matter and index entries. Home stretch now. Revision 17—(July 8, 2003) Chapters 5 and 11 are 90% done! Revision 16—(June 25, 2003) Chapter 5 text is almost complete, but enough is added to justify a separate posting. The example programs for Chapter 11 are also fairly complete. Added a matrix multiplication example to the valarray material in chapter 7. Chapter 7 has been tech-edited. Many corrections due to comments from users have been integrated into the text (thanks!). Revision 15—(March 1 ,2003) Fixed an omission in C10:CuriousSingleton.cpp. Chapters 9 and 10 have been tech-edited. Revision 14—(January ,2003) Fixed a number of fuzzy explanations in response to reader feedback (thanks!). Chapter 9 has been copy-edited. Revision 13—(December 31, 2002) Updated the exercises for Chapter 7. Finished rewriting Chapter 9. Added a template variation of Singleton to chapter 10. Updated the build directives. Fixed lots of stuff. Chapters 5 and 11 still await rewrite. Revision 12—(December 23, 2002) Added material on Design Patterns as Chapter 10 (Concurrency will move to Chapter 11).
    [Show full text]
  • BSDLUA Slides (Application/Pdf
    BSDLUA (in three parts) Evolved Unix Scripting Ivan Voras <[email protected]> What is BSDLUA? ● An experimental idea ● Use Lua for projects, tools, etc. which do not require C and would be more easily implemented in a scripting language ● An “in between” language – low-level features of C with integration capabilities of shell scripts Why??? ● The $1M question: what in the world would make someone program in something which is not /bin/sh ??? ● /bin/sh is the best thing since the invention of the bicycle... from the time when Unix programmers had real beards... (More specifically) ● I personally miss a “higher level” scripting language in the base system ● In the beginning there was TCL (or so I heard... it was before my time) ● The there was Perl... ● Both were thrown out – For good reasons What is wrong with shell scripts? ● Nothing … and everything ● Good sides: integration with system tools via executing programs, sourcing other scripts ● Bad sides: … somewhat depend on personal tastes … for me it's the syntax and lack of modern features ● Talking about the /bin/sh POSIX shell – more modern shells have nicer languages Why not use /bin/sh? ● (for complex programs) ● Syntax from the 1970-ies ● No local variables ● No “proper” functions (with declared arguments) ● Need to escape strings more often than what would sanely be expected ● Relies on external tools for common operations (tr, grep, join, jot, awk...) ● Too much “magic” in operation Why use Lua? (1) ● As a language: ● Nicer, modern language with lexical scoping ● Namespaces
    [Show full text]