Scala-Quick-Reference.Pdf

Total Page:16

File Type:pdf, Size:1020Kb

Scala-Quick-Reference.Pdf Symbolics Operators Import import java.awt._ // All classes under java.awt -> Returns a two-element Map( 1 -> "A", 2 -> "B") +, -, *, /, % Arithmetics import java.io.File tuple containing the key (1).->(“A”) >, < ,<=, >=, ==, != Relational import java.io.File._ // Import all Fileʼ static methods and value &&, ||, ! Logical import java.util.{Map, HashMap} // only the 2 classes _ A placeholder, used in import com.xtech._ imports, function literals, &, |, ^, ~ Bitwise Narrow import: case _ => value.toString (and, or, xor, inv) etc. numbers.filter(_ < 0) def doIt() = { <<, >>, >>> Bitwise shift import java.math.BigDecimal.{ONE} : Separator between def add(i: Int): Int = ... (left, right, unsigned right) identifiers and type println(ONE) annotations. } The operator “==” check the value equality on = Assignment. val one = “1” reference AND primitive type. Rename import: import java.math.BigDecimal.{ ONE => _, ## // Exclude ONE => Used in function literals numbers.filter(x => x < 0) Rich Operation ZERO => JAVAZERO # // Rename it to separate the argument } ! list from the function Scala provides “rich wrapper” around basic types via implicit println(JAVAZERO) body. conversions. <- Used in for for (arg <- args) import statements are relative, not absolute. To " comprehensions in Code Result create an absolute path, start with _root_ generator expressions. 0 max 5 5 <: Upper bounds (a subtype def apply[T <: U](x: T) import _root_.scala.collectionsjcl._ of)Used in parameterized 0 min 5 0 and abstract type -2.7 abs 2.7 Packages declarations to constrain -2.7 round -3L the allowed types. File names don’t have to match the type names, 1.5 isInfinity false the package structure does not have to match the <% View bounds( apply def m [A <% B](args): R directory structure. So, you can define packages in implicit convertion).Used = ... (1.0 / 0) isInfinity true files independent of their “physical” location. in parameterized and 4 to 6 Range(4,5,6) abstract type declarations Traditional: to convert the type using "nick" capitalize “Nick” package com.xtech.scala view. "nicolas" drop 2 “colas” Nested: >: Lower bounds (supertype def append[U >: T](x: U) package com{ of)Used in parameterized = Literals and abstract type package scala { class A } declarations to constrain Integer package util { class B } } the allowed types. val dec = 31 Decimal Integer # Refer to a type val ic: MyClass#myType val hex = 0XFF Hexa Integer Tuples declaration nested in = ... another type val long = 31L Long (“l” or “L”) Are immutable and can contain different types of elements. @ Marks an annotation. @deprecated def bad() = val little: Short = 367 Short val nena = (99, "Luftballons",”1983”) ʻ Symbol val s = 'aSymbol val littler: Byte = 38 Byte println(nena._1) def doIt(r: Symbol) println(nena._2) .... println(nena(0)) (not same Type in list) doIt(s); print(s.name) Floating point val double = 1.2345 Double _ Usage Summary Curried functions If a method takes 0 or one parameter you can drop val e = 1.234e4 Double (“e” or “E”) the dot and parentheses when calling the function. val float = 1.234F Float (“f” or “F”) def twice(op: Double => Double) (x: Double) = op(op(x)) twice(_ + 1) (5) Character and String res8: Double = 7.0 Variables val aChar = ʻDʼ Char twice(x => x + 1)(5) // More verbose Immutable (Final) val unicode = ʼ\u0043ʼ Unicode Char Existential types val msg = "Hello, world!" val string = “string” String Labeling something that is unknown: val msg: String = "Hello, world!" val s = “”” itʼs “you” “”” Raw String ( It’s “you” ) class Marshaller[T] { def marshall(t:T) = {println(t)} } val big = new java.math.BigInteger("12345") new Marshaller[String] Mutable Special character res1: Marshaller[String] = Marshaller@7896b1b8 var greets = "Hello, world!" Literal Meaning res1.isInstanceOf[Marshaller[_]] var greets: String = "Hello, world!" res4: Boolean = true \n line feed (\u000A) Lazy initialization same as: (only on Immutable) \b backspace (\u0008) .isInstanceOf[T forSome {type T <: Marshaller[String]}] object Demo { \t tab (\u0009) Function literals lazy val x = { println("initializing x"); "done" } \f form feed (\u000C) } someNumbers.filter(_ > 0) \r carriage return (\u000D) Partially applied functions Basic Types \” double quote (\u0022) def sum(a: Int, b: Int, c: Int) = a + b + c Value Type Range \’ single quote (\u0027) val a = sum _ Byte 8-bit signed two’s complement integer \\ backslash (\u005C) a: (Int, Int, Int) => Int = <function> (-27 to 27 - 1, inclusive) val b = sum(1, _: Int, 3) Boolean Short 16-bit signed two’s complement integer b: (Int) => Int = <function> (-215 to 215 - 1, inclusive) val bool = true Boolean (true | false) b(2) Int 32-bit signed two’s complement integer Check res10: Int = 6 (-231 to 231 - 1, inclusive) “abc”.isInstanceOf[String] Import statements Long 64-bit signed two’s complement integer (-263 to 263 - 1, inclusive) re0: Boolean = true import com.xtech.cf._ Char 16-bit unsigned Unicode character Cast Match expressions (0 to 216 - 1, inclusive) 3.asInstanceOf[Double] case _ => “default value” // Default case value String a sequence of Chars res0: Double = 3.0 Initialization Float 32-bit IEEE 754 single-precision float Runtime Representation Double 64-bit IEEE 754 double-precision float var age: Int = _ // age initialized to 0 Boolean true or false classOf[String] Setter res7: java.lang.Class[String] = class java.lang.String Redefined a setter method: def age_ = (a: Int) { if(girl) age = a - 5 else age = a } [email protected]!!!!!!1 / 6!! ! ! ! ! ! v. 1.1 Class Hierachy Variance Actors Covariance: Ability to accept sub-classes. import scala.actors._ Any “T <: Pet” or “+T” : (as T extends Pet) object SimpleActor extends Actor { Equivalent to def act() { java.long.Object Contra-variance: Ability to accept base classes “T >: Cat” or “-T” : (as T is superType of Cat) for (i <- 1 to 5) { AnyVal AnyRef println("Do it!") Traits Thread.sleep(1000) } A traits is like a java interface at the difference that it’s Unit Double ScalaObject possible to implements methods and fields on it. Traits can } be reused into classes by mixing the trait to the class or by } extending it. All java.* All scala.* Boolean Float To Start it: ref. types ref. types Definition SimpleActor.start() trait Saxo { def play() { To start a thread immediately use the utility method actor: import scala.actors._ println("Nice sound!") val seriousActor2 = actor { } for (i <- 1 to 5) Helper for type } Null inference println("Do it!.") Extends } Nothing class Alto extends Saxo { override def toString = "Alto" Send message to Actor; import scala.actors._ } Definition val echoActor = actor { With while (true) { Simple class: class Instrument receive { class ChecksumAccumulator { class Baryton extends Instrument { case msg => println("received message: "+ msg) private var sum = 0 override def toString = "Baryton" } def add(b: Byte): Unit = sum += b } } def checksum(): Int = ~(sum & 0xFF) + 1 val baryton = new Baryton() with Saxo } } Ordered Traits To send a message: Constructor echoActor ! “Hello” The Ordered trait defines <, >, <=, and >= just by received message: hi there The default constructor (primary constructor) is defined by implementing one method, compare. the body class and parameters are listed after the class class Rational(n: Int, d: Int) extends Ordered[Rational]{ To use the current thread use self: name. Other constructors (auxiliary constructor) are defined // ... self ! "hello" by the function definition “this()”: def compare(that: Rational) = self.receive { case x => x } class Rational(n: Int, d: Int) { (this.numer * that.denom) - (that.numer * this.denom) res6: Any = hello require(d != 0) } self.receiveWithin(1000) { case x => x } res7: Any = TIMEOUT val numer: Int = n Mixing val denom: Int = d Change Scheduler: def this(n: Int) = this(n, 1) // auxiliary constructor Once a trait is mixed into a class, you can alternatively call it } a mixin.Traits are a way to inherit from multiple class-like Run it on the main Thread constructs, but they differ in important ways from the trait SingleThread extends Actor{ To hide the constructor make it private: multiple inheritance present in many languages. With traits, override protected def scheduler() = class Rational private(n: Int, d: Int) the method called is determined by a linearization of the ## new SingleThreadScheduler classes and traits that are mixed into a class. } Getter / Setter Linearization algorithm Run all actors in the Main thread: Once a val or var is defined within a class the corresponding Scheduler.impl = new SingleThreadScheduler accessor methods are generated. The generated methods 1 Put the actual type of the instance as the first element. use the same privilege as the field. Thread reuse Only the getter is generated in case of val. 2 Starting with the right most parent type and working The methods don’t follow the JavaBean nomenclature. left,compute the linearization of each type, appending Writing an actor to use react instead of receive is its linearization to the cumulative linearization. (Ignore challenging, but pays off in performance. Because react To generate JavaBean getter and setter add the annotation: ScalaObject, AnyRef, and Any for now.) does not return, the calling actor’s call stack can be @scala.reflect.BeanProperty var level: Int = _ discarded, freeing up the thread’s resources for a different actor. At the extreme, if all of the actors of a program use Abstract 3 Working from left to right, remove any type if it react, then they can be implemented on a single thread. abstract class Document { appears again to the right of the current position. As empiric rule: def footNotes: Array[String] // abstract method 4 Append ScalaObject, AnyRef, and Any. - Actors that are message-heavy are better implemented var nbOfPages : Int // abstract Field class C1 {def m = List("C1")} with “while(true)/receive” (Hogging a thread). - Actors with non trivial work are better implemented with type paper# // abstract type trait T1 extends C1 {override def m ={ "T1" :: super.m}} } “loop/react”.
Recommended publications
  • Practical Perl Tools: Scratch the Webapp Itch With
    last tIme, we had the pleasure oF exploring the basics of a Web applica- DaviD n. BLank-EdeLman tion framework called CGI::Application (CGI::App). I appreciate this particular pack- age because it hits a certain sweet spot in practical Perl tools: terms of its complexity/learning curve and scratch the webapp itch with power. In this column we’ll finish up our exploration by looking at a few of the more CGI::Application, part 2 powerful extensions to the framework that David N. Blank-Edelman is the director of can really give it some oomph. technology at the Northeastern University College of Computer and Information Sci- ence and the author of the O’Reilly book Quick review Automating System Administration with Perl (the second edition of the Otter book), Let’s do a really quick review of how CGI::App available at purveyors of fine dead trees works, so that we can build on what we’ve learned everywhere. He has spent the past 24+ years as a system/network administrator in large so far. CGI::App is predicated on the notion of “run multi-platform environments, including modes.” When you are first starting out, it is easi- Brandeis University, Cambridge Technology est to map “run mode” to “Web page” in your head. Group, and the MIT Media Laboratory. He was the program chair of the LISA ’05 confer- You write a piece of code (i.e., a subroutine) that ence and one of the LISA ’06 Invited Talks will be responsible for producing the HTML for co-chairs.
    [Show full text]
  • Object Oriented Programming in Java Object Oriented
    Object Oriented Programming in Java Introduction Object Oriented Programming in Java Introduction to Computer Science II I Java is Object-Oriented I Not pure object oriented Christopher M. Bourke I Differs from other languages in how it achieves and implements OOP [email protected] functionality I OOP style programming requires practice Objects in Java Objects in Java Java is a class-based OOP language Definition Contrast with proto-type based OOP languages A class is a construct that is used as a blueprint to create instances of I Example: JavaScript itself. I No classes, only instances (of objects) I Constructed from nothing (ex-nihilo) I Objects are concepts; classes are Java’s realization of that concept I Inheritance through cloning of original prototype object I Classes are a definition of all objects of a specific type (instances) I Interface is build-able, mutable at runtime I Classes provide an explicit blueprint of its members and their visibility I Instances of a class must be explicitly created Objects in Java Objects in JavaI Paradigm: Singly-Rooted Hierarchy Object methods 1 //ignore: 2 protected Object clone(); 3 protected void finalize(); I All classes are subclasses of Object 4 Class<? extends Object> getClass(); 5 I Object is a java object, not an OOP object 6 //multithreaded applications: I Makes garbage collection easier 7 public void notify(); 8 public void notifyAll(); I All instances have a type and that type can be determined 9 public void wait(); I Provides a common, universal minimum interface for objects 10 public
    [Show full text]
  • Process Synchronisation Background (1)
    Process Synchronisation Background (1) Concurrent access to shared data may result in data inconsistency Maintaining data consistency requires mechanisms to ensure the orderly execution of cooperating processes Producer Consumer Background (2) Race condition count++ could be implemented as register1 = count register1 = register1 + 1 count = register1 count- - could be implemented as register2 = count register2 = register2 - 1 count = register2 Consider this execution interleaving with ―count = 5‖ initially: S0: producer execute register1 = count {register1 = 5} S1: producer execute register1 = register1 + 1 {register1 = 6} S2: consumer execute register2 = count {register2 = 5} S3: consumer execute register2 = register2 - 1 {register2 = 4} S4: producer execute count = register1 {count = 6 } S5: consumer execute count = register2 {count = 4} Solution: ensure that only one process at a time can manipulate variable count Avoid interference between changes Critical Section Problem Critical section: a segment of code in which a process may be changing Process structure common variables ◦ Only one process is allowed to be executing in its critical section at any moment in time Critical section problem: design a protocol for process cooperation Requirements for a solution ◦ Mutual exclusion ◦ Progress ◦ Bounded waiting No assumption can be made about the relative speed of processes Handling critical sections in OS ◦ Pre-emptive kernels (real-time programming, more responsive) Linux from 2.6, Solaris, IRIX ◦ Non-pre-emptive kernels (free from race conditions) Windows XP, Windows 2000, traditional UNIX kernel, Linux prior 2.6 Peterson’s Solution Two process solution Process Pi ◦ Mutual exclusion is preserved? ◦ The progress requirements is satisfied? ◦ The bounded-waiting requirement is met? Assumption: LOAD and STORE instructions are atomic, i.e.
    [Show full text]
  • Gnu Smalltalk Library Reference Version 3.2.5 24 November 2017
    gnu Smalltalk Library Reference Version 3.2.5 24 November 2017 by Paolo Bonzini Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later version published by the Free Software Foundation; with no Invariant Sections, with no Front-Cover Texts, and with no Back-Cover Texts. A copy of the license is included in the section entitled \GNU Free Documentation License". 1 3 1 Base classes 1.1 Tree Classes documented in this manual are boldfaced. Autoload Object Behavior ClassDescription Class Metaclass BlockClosure Boolean False True CObject CAggregate CArray CPtr CString CCallable CCallbackDescriptor CFunctionDescriptor CCompound CStruct CUnion CScalar CChar CDouble CFloat CInt CLong CLongDouble CLongLong CShort CSmalltalk CUChar CByte CBoolean CUInt CULong CULongLong CUShort ContextPart 4 GNU Smalltalk Library Reference BlockContext MethodContext Continuation CType CPtrCType CArrayCType CScalarCType CStringCType Delay Directory DLD DumperProxy AlternativeObjectProxy NullProxy VersionableObjectProxy PluggableProxy SingletonProxy DynamicVariable Exception Error ArithmeticError ZeroDivide MessageNotUnderstood SystemExceptions.InvalidValue SystemExceptions.EmptyCollection SystemExceptions.InvalidArgument SystemExceptions.AlreadyDefined SystemExceptions.ArgumentOutOfRange SystemExceptions.IndexOutOfRange SystemExceptions.InvalidSize SystemExceptions.NotFound SystemExceptions.PackageNotAvailable SystemExceptions.InvalidProcessState SystemExceptions.InvalidState
    [Show full text]
  • Learning Javascript Design Patterns
    Learning JavaScript Design Patterns Addy Osmani Beijing • Cambridge • Farnham • Köln • Sebastopol • Tokyo Learning JavaScript Design Patterns by Addy Osmani Copyright © 2012 Addy Osmani. All rights reserved. Revision History for the : 2012-05-01 Early release revision 1 See http://oreilly.com/catalog/errata.csp?isbn=9781449331818 for release details. ISBN: 978-1-449-33181-8 1335906805 Table of Contents Preface ..................................................................... ix 1. Introduction ........................................................... 1 2. What is a Pattern? ...................................................... 3 We already use patterns everyday 4 3. 'Pattern'-ity Testing, Proto-Patterns & The Rule Of Three ...................... 7 4. The Structure Of A Design Pattern ......................................... 9 5. Writing Design Patterns ................................................. 11 6. Anti-Patterns ......................................................... 13 7. Categories Of Design Pattern ............................................ 15 Creational Design Patterns 15 Structural Design Patterns 16 Behavioral Design Patterns 16 8. Design Pattern Categorization ........................................... 17 A brief note on classes 17 9. JavaScript Design Patterns .............................................. 21 The Creational Pattern 22 The Constructor Pattern 23 Basic Constructors 23 Constructors With Prototypes 24 The Singleton Pattern 24 The Module Pattern 27 iii Modules 27 Object Literals 27 The Module Pattern
    [Show full text]
  • Better PHP Development I
    Better PHP Development i Better PHP Development Copyright © 2017 SitePoint Pty. Ltd. Cover Design: Natalia Balska Notice of Rights All rights reserved. No part of this book may be reproduced, stored in a retrieval system or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embodied in critical articles or reviews. Notice of Liability The author and publisher have made every effort to ensure the accuracy of the information herein. However, the information contained in this book is sold without warranty, either express or implied. Neither the authors and SitePoint Pty. Ltd., nor its dealers or distributors will be held liable for any damages to be caused either directly or indirectly by the instructions contained in this book, or by the software or hardware products described herein. Trademark Notice Rather than indicating every occurrence of a trademarked name as such, this book uses the names only in an editorial fashion and to the benefit of the trademark owner with no intention of infringement of the trademark. Published by SitePoint Pty. Ltd. 48 Cambridge Street Collingwood VIC Australia 3066 Web: www.sitepoint.com Email: [email protected] ii Better PHP Development About SitePoint SitePoint specializes in publishing fun, practical, and easy-to-understand content for web professionals. Visit http://www.sitepoint.com/ to access our blogs, books, newsletters, articles, and community forums. You’ll find a stack of information on JavaScript, PHP, design,
    [Show full text]
  • Introducing Javascript OSA
    Introducing JavaScript OSA Late Night SOFTWARE Contents CHAPTER 1 What is JavaScript OSA?....................................................................... 1 The OSA ........................................................................................................................ 2 Why JavaScript? ............................................................................................................ 3 CHAPTER 2 JavaScript Examples.............................................................................. 5 Learning JavaScript ....................................................................................................... 6 Sieve of Eratosthenes..................................................................................................... 7 Word Histogram Example ............................................................................................. 8 Area of a Polygon .......................................................................................................... 9 CHAPTER 3 The Core Object ................................................................................... 13 Talking to the User ...................................................................................................... 14 Places ........................................................................................................................... 14 Where Am I?................................................................................................................ 14 Who Am I? .................................................................................................................
    [Show full text]
  • Concepts in Programming Languages Practicalities
    Concepts in Programming Languages Practicalities I Course web page: Alan Mycroft1 www.cl.cam.ac.uk/teaching/1617/ConceptsPL/ with lecture slides, exercise sheet and reading material. These slides play two roles – both “lecture notes" and “presentation material”; not every slide will be lectured in Computer Laboratory detail. University of Cambridge I There are various code examples (particularly for 2016–2017 (Easter Term) JavaScript and Java applets) on the ‘materials’ tab of the course web page. I One exam question. www.cl.cam.ac.uk/teaching/1617/ConceptsPL/ I The syllabus and course has changed somewhat from that of 2015/16. I would be grateful for comments on any remaining ‘rough edges’, and for views on material which is either over- or under-represented. 1Acknowledgement: various slides are based on Marcelo Fiore’s 2013/14 course. Alan Mycroft Concepts in Programming Languages 1 / 237 Alan Mycroft Concepts in Programming Languages 2 / 237 Main books Context: so many programming languages I J. C. Mitchell. Concepts in programming languages. Cambridge University Press, 2003. Peter J. Landin: “The Next 700 Programming Languages”, I T.W. Pratt and M. V.Zelkowitz. Programming Languages: CACM (published in 1966!). Design and implementation (3RD EDITION). Some programming-language ‘family trees’ (too big for slide): Prentice Hall, 1999. http://www.oreilly.com/go/languageposter http://www.levenez.com/lang/ ? M. L. Scott. Programming language pragmatics http://rigaux.org/language-study/diagram.html (4TH EDITION). http://www.rackspace.com/blog/ Elsevier, 2016. infographic-evolution-of-computer-languages/ I R. Harper. Practical Foundations for Programming Plan of this course: pick out interesting programming-language Languages.
    [Show full text]
  • Bespoke Tools: Adapted to the Concepts Developers Know
    Bespoke Tools: Adapted to the Concepts Developers Know Brittany Johnson, Rahul Pandita, Emerson Murphy-Hill, and Sarah Heckman Department of Computer Science North Carolina State University, Raleigh, NC, USA {bijohnso, rpandit}@ncsu.edu, {emerson, heckman}@csc.ncsu.edu ABSTRACT Such manual customization is undesirable for several rea- Even though different developers have varying levels of ex- sons. First, to choose among alternative tools, a developer pertise, the tools in one developer's integrated development must be aware that alternatives exist, yet lack of awareness environment (IDE) behave the same as the tools in every is a pervasive problem in complex software like IDEs [3]. other developers' IDE. In this paper, we propose the idea of Second, even after being aware of alternatives, she must be automatically customizing development tools by modeling able to intelligently choose which tool will be best for her. what a developer knows about software concepts. We then Third, if a developer's situation changes and she recognizes sketch three such \bespoke" tools and describe how devel- that the tool she is currently using is no longer the optimal opment data can be used to infer what a developer knows one, she must endure the overhead of switching to another about relevant concepts. Finally, we describe our ongoing ef- tool. Finally, customization takes time, time that is spent forts to make bespoke program analysis tools that customize fiddling with tools rather than developing software. their notifications to the developer using them. 2. WHAT IS THE NEW IDEA? Categories and Subject Descriptors Our idea is bespoke tools: tools that automatically fit D.2.6 [Software Engineering]: Programming Environments| themselves to the developer using them.
    [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]
  • The C Programming Language
    The C programming Language The C programming Language By Brian W. Kernighan and Dennis M. Ritchie. Published by Prentice-Hall in 1988 ISBN 0-13-110362-8 (paperback) ISBN 0-13-110370-9 Contents ● Preface ● Preface to the first edition ● Introduction 1. Chapter 1: A Tutorial Introduction 1. Getting Started 2. Variables and Arithmetic Expressions 3. The for statement 4. Symbolic Constants 5. Character Input and Output 1. File Copying 2. Character Counting 3. Line Counting 4. Word Counting 6. Arrays 7. Functions 8. Arguments - Call by Value 9. Character Arrays 10. External Variables and Scope 2. Chapter 2: Types, Operators and Expressions 1. Variable Names 2. Data Types and Sizes 3. Constants 4. Declarations http://freebooks.by.ru/view/CProgrammingLanguage/kandr.html (1 of 5) [5/15/2002 10:12:59 PM] The C programming Language 5. Arithmetic Operators 6. Relational and Logical Operators 7. Type Conversions 8. Increment and Decrement Operators 9. Bitwise Operators 10. Assignment Operators and Expressions 11. Conditional Expressions 12. Precedence and Order of Evaluation 3. Chapter 3: Control Flow 1. Statements and Blocks 2. If-Else 3. Else-If 4. Switch 5. Loops - While and For 6. Loops - Do-While 7. Break and Continue 8. Goto and labels 4. Chapter 4: Functions and Program Structure 1. Basics of Functions 2. Functions Returning Non-integers 3. External Variables 4. Scope Rules 5. Header Files 6. Static Variables 7. Register Variables 8. Block Structure 9. Initialization 10. Recursion 11. The C Preprocessor 1. File Inclusion 2. Macro Substitution 3. Conditional Inclusion 5. Chapter 5: Pointers and Arrays 1.
    [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]