Programming in Scala

Total Page:16

File Type:pdf, Size:1020Kb

Programming in Scala Programming in Scala DRAFT May 21, 2007 Martin Odersky PROGRAMMING METHODS LABORATORY EPFL SWITZERLAND Contents I Rationale 1 II Scala by Example 7 1 A First Example 11 2 Programming with Actors and Messages 15 3 Expressions and Simple Functions 19 3.1 Expressions And Simple Functions ...................... 19 3.2 Parameters .................................... 20 3.3 Conditional Expressions ............................ 23 3.4 Example: Square Roots by Newton’s Method ................ 23 3.5 Nested Functions ................................ 24 3.6 Tail Recursion .................................. 26 4 First-Class Functions 29 4.1 Anonymous Functions ............................. 30 4.2 Currying ..................................... 31 4.3 Example: Finding Fixed Points of Functions ................ 34 4.4 Summary ..................................... 36 4.5 Language Elements Seen So Far ....................... 36 5 Classes and Objects 39 6 Case Classes and Pattern Matching 51 6.1 Case Classes and Case Objects ........................ 54 6.2 Pattern Matching ................................ 55 iv CONTENTS 7 Generic Types and Methods 59 7.1 Type Parameter Bounds ............................ 61 7.2 Variance Annotations .............................. 64 7.3 Lower Bounds .................................. 66 7.4 Least Types .................................... 66 7.5 Tuples ....................................... 68 7.6 Functions .................................... 69 8 Lists 71 8.1 Using Lists .................................... 71 8.2 Definition of class List I: First Order Methods ............... 73 8.3 Example: Merge sort .............................. 76 8.4 Definition of class List II: Higher-Order Methods ............. 78 8.5 Summary ..................................... 85 9 For-Comprehensions 87 9.1 The N-Queens Problem ............................ 88 9.2 Querying with For-Comprehensions ..................... 89 9.3 Translation of For-Comprehensions ..................... 90 9.4 For-Loops .................................... 92 9.5 Generalizing For ................................. 92 10 Mutable State 95 10.1 Stateful Objects ................................. 95 10.2 Imperative Control Structures ......................... 99 10.3 Extended Example: Discrete Event Simulation ............... 100 10.4 Summary ..................................... 105 11 Computing with Streams 107 12 Iterators 111 12.1 Iterator Methods ................................ 111 12.2 Constructing Iterators ............................. 114 12.3 Using Iterators .................................. 115 CONTENTS v 13 Implicit Parameters and Conversions 117 14 Combinator Parsing 121 14.1 Simple Combinator Parsing .......................... 121 14.2 Parsers that Produce Results ......................... 125 15 Hindley/Milner Type Inference 131 16 Abstractions for Concurrency 141 16.1 Signals and Monitors .............................. 141 16.2 SyncVars ..................................... 143 16.3 Futures ...................................... 143 16.4 Parallel Computations ............................. 144 16.5 Semaphores ................................... 145 16.6 Readers/Writers ................................. 145 16.7 Asynchronous Channels ............................ 146 16.8 Synchronous Channels ............................. 147 16.9 Workers ...................................... 148 16.10Mailboxes .................................... 150 16.11Actors ....................................... 153 III The Scala Language Specification Version 1.0 155 17 Lexical Syntax 159 17.1 Identifiers .................................... 160 17.2 Newline Characters ............................... 161 17.3 Literals ...................................... 164 17.3.1 Integer Literals ............................. 164 17.3.2 Floating Point Literals ......................... 165 17.3.3 Boolean Literals ............................. 166 17.3.4 Character Literals ............................ 166 17.3.5 String Literals .............................. 166 17.3.6 Escape Sequences ........................... 167 vi CONTENTS 17.3.7 Symbol literals .............................. 168 17.4 Whitespace and Comments .......................... 168 17.5 XML mode .................................... 169 18 Identifiers, Names and Scopes 171 19 Types 173 19.1 Paths ....................................... 174 19.2 Value Types ................................... 174 19.2.1 Singleton Types ............................. 174 19.2.2 Type Projection ............................. 175 19.2.3 Type Designators ............................ 175 19.2.4 Parameterized Types .......................... 175 19.2.5 Tuple Types ............................... 176 19.2.6 Annotated Types ............................ 177 19.2.7 Compound Types ............................ 177 19.2.8 Infix Types ................................ 177 19.2.9 Function Types ............................. 178 19.2.10Primitive Types Defined in Predef .................. 178 19.3 Non-Value Types ................................ 179 19.3.1 Method Types .............................. 179 19.3.2 Polymorphic Method Types ...................... 180 19.3.3 Type Constructors ........................... 180 19.4 Base Types and Member Definitions ..................... 180 19.5 Relations between types ............................ 182 19.5.1 Type Equivalence ............................ 182 19.5.2 Conformance .............................. 183 19.6 Type Erasure ................................... 185 20 Basic Declarations and Definitions 187 20.1 Value Declarations and Definitions ..................... 187 20.2 Variable Declarations and Definitions .................... 189 20.3 Type Declarations and Type Aliases ..................... 190 20.4 Type Parameters ................................. 192 CONTENTS vii 20.5 Variance Annotations .............................. 193 20.6 Function Declarations and Definitions ................... 195 20.6.1 By-Name Parameters .......................... 196 20.6.2 Repeated Parameters .......................... 197 20.6.3 Procedures ................................ 198 20.6.4 Method Return Type Inference .................... 198 20.7 Import Clauses ................................. 199 21 Classes and Objects 201 21.1 Templates .................................... 201 21.1.1 Constructor Invocations ........................ 203 21.1.2 Class Linearization ........................... 203 21.1.3 Class Members ............................. 204 21.1.4 Overriding ................................ 206 21.1.5 Inheritance Closure .......................... 206 21.1.6 Early Definitions ............................ 207 21.2 Modifiers ..................................... 208 21.3 Class Definitions ................................ 211 21.3.1 Constructor Definitions ........................ 213 21.3.2 Case Classes ............................... 214 21.3.3 Traits ................................... 215 21.4 Object Definitions ............................... 217 22 Expressions 219 22.1 Literals ...................................... 220 22.2 The Null Value .................................. 220 22.3 Designators ................................... 221 22.4 This and Super ................................. 221 22.5 Function Applications ............................. 222 22.6 Method Values .................................. 224 22.7 Type Applications ................................ 224 22.8 Tuples ....................................... 225 22.9 Instance Creation Expressions ........................ 225 22.10Blocks ....................................... 225 viii CONTENTS 22.11Prefix, Infix, and Postfix Operations ..................... 226 22.11.1Prefix Operations ............................ 227 22.11.2Postfix Operations ........................... 227 22.11.3Infix Operations ............................. 227 22.11.4Assignment Operators ......................... 228 22.12Typed Expressions ............................... 228 22.13Annotated Expressions ............................. 229 22.14Assignments ................................... 229 22.15Conditional Expressions ............................ 230 22.16WhileLoop Expressions ............................ 231 22.17DoLoop Expressions .............................. 231 22.18For-Comprehensions .............................. 231 22.19Return Expressions ............................... 234 22.20Throw Expressions ............................... 234 22.21Try Expressions ................................. 234 22.22Anonymous Functions ............................. 235 22.23Statements .................................... 237 22.24Implicit Conversions .............................. 238 22.24.1Value Conversions ........................... 238 22.24.2Method Conversions .......................... 238 22.24.3Overloading Resolution ........................ 239 22.24.4Local Type Inference .......................... 240 22.24.5Eta Expansion .............................. 243 23 Implicit Parameters and Views 245 23.1 The Implicit Modifier .............................. 245 23.2 Implicit Parameters ............................... 246 23.3 Views ....................................... 248 23.4 View Bounds ................................... 249 24 Pattern Matching 251 24.1 Patterns ...................................... 251 24.1.1 Variable Patterns ............................ 252 24.1.2 Typed Patterns ............................. 252 CONTENTS ix 24.1.3 Literal Patterns ............................. 252 24.1.4 Stable Identifier
Recommended publications
  • Lecture 4. Higher-Order Functions Functional Programming
    Lecture 4. Higher-order functions Functional Programming [Faculty of Science Information and Computing Sciences] 0 I function call and return as only control-flow primitive I no loops, break, continue, goto I (almost) unique types I no inheritance hell I high-level declarative data-structures I no explicit reference-based data structures Goal of typed purely functional programming Keep programs easy to reason about by I data-flow only through function arguments and return values I no hidden data-flow through mutable variables/state [Faculty of Science Information and Computing Sciences] 1 I (almost) unique types I no inheritance hell I high-level declarative data-structures I no explicit reference-based data structures Goal of typed purely functional programming Keep programs easy to reason about by I data-flow only through function arguments and return values I no hidden data-flow through mutable variables/state I function call and return as only control-flow primitive I no loops, break, continue, goto [Faculty of Science Information and Computing Sciences] 1 I high-level declarative data-structures I no explicit reference-based data structures Goal of typed purely functional programming Keep programs easy to reason about by I data-flow only through function arguments and return values I no hidden data-flow through mutable variables/state I function call and return as only control-flow primitive I no loops, break, continue, goto I (almost) unique types I no inheritance hell [Faculty of Science Information and Computing Sciences] 1 Goal
    [Show full text]
  • Higher-Order Functions 15-150: Principles of Functional Programming – Lecture 13
    Higher-order Functions 15-150: Principles of Functional Programming { Lecture 13 Giselle Reis By now you might feel like you have a pretty good idea of what is going on in functional program- ming, but in reality we have used only a fragment of the language. In this lecture we see what more we can do and what gives the name functional to this paradigm. Let's take a step back and look at ML's typing system: we have basic types (such as int, string, etc.), tuples of types (t*t' ) and functions of a type to a type (t ->t' ). In a grammar style (where α is a basic type): τ ::= α j τ ∗ τ j τ ! τ What types allowed by this grammar have we not used so far? Well, we could, for instance, have a function below a tuple. Or even a function within a function, couldn't we? The following are completely valid types: int*(int -> int) int ->(int -> int) (int -> int) -> int The first one is a pair in which the first element is an integer and the second one is a function from integers to integers. The second one is a function from integers to functions (which have type int -> int). The third type is a function from functions to integers. The two last types are examples of higher-order functions1, i.e., a function which: • receives a function as a parameter; or • returns a function. Functions can be used like any other value. They are first-class citizens. Maybe this seems strange at first, but I am sure you have used higher-order functions before without noticing it.
    [Show full text]
  • Reversible Programming with Negative and Fractional Types
    9 A Computational Interpretation of Compact Closed Categories: Reversible Programming with Negative and Fractional Types CHAO-HONG CHEN, Indiana University, USA AMR SABRY, Indiana University, USA Compact closed categories include objects representing higher-order functions and are well-established as models of linear logic, concurrency, and quantum computing. We show that it is possible to construct such compact closed categories for conventional sum and product types by defining a dual to sum types, a negative type, and a dual to product types, a fractional type. Inspired by the categorical semantics, we define a sound operational semantics for negative and fractional types in which a negative type represents a computational effect that “reverses execution flow” and a fractional type represents a computational effect that“garbage collects” particular values or throws exceptions. Specifically, we extend a first-order reversible language of type isomorphisms with negative and fractional types, specify an operational semantics for each extension, and prove that each extension forms a compact closed category. We furthermore show that both operational semantics can be merged using the standard combination of backtracking and exceptions resulting in a smooth interoperability of negative and fractional types. We illustrate the expressiveness of this combination by writing a reversible SAT solver that uses back- tracking search along freshly allocated and de-allocated locations. The operational semantics, most of its meta-theoretic properties, and all examples are formalized in a supplementary Agda package. CCS Concepts: • Theory of computation → Type theory; Abstract machines; Operational semantics. Additional Key Words and Phrases: Abstract Machines, Duality of Computation, Higher-Order Reversible Programming, Termination Proofs, Type Isomorphisms ACM Reference Format: Chao-Hong Chen and Amr Sabry.
    [Show full text]
  • Dotty Phantom Types (Technical Report)
    Dotty Phantom Types (Technical Report) Nicolas Stucki Aggelos Biboudis Martin Odersky École Polytechnique Fédérale de Lausanne Switzerland Abstract 2006] and even a lightweight form of dependent types [Kise- Phantom types are a well-known type-level, design pattern lyov and Shan 2007]. which is commonly used to express constraints encoded in There are two ways of using phantoms as a design pattern: types. We observe that in modern, multi-paradigm program- a) relying solely on type unication and b) relying on term- ming languages, these encodings are too restrictive or do level evidences. According to the rst way, phantoms are not provide the guarantees that phantom types try to en- encoded with type parameters which must be satised at the force. Furthermore, in some cases they introduce unwanted use-site. The declaration of turnOn expresses the following runtime overhead. constraint: if the state of the machine, S, is Off then T can be We propose a new design for phantom types as a language instantiated, otherwise the bounds of T are not satisable. feature that: (a) solves the aforementioned issues and (b) makes the rst step towards new programming paradigms type State; type On <: State; type Off <: State class Machine[S <: State] { such as proof-carrying code and static capabilities. This pa- def turnOn[T >: S <: Off] = new Machine[On] per presents the design of phantom types for Scala, as im- } new Machine[Off].turnOn plemented in the Dotty compiler. An alternative way to encode the same constraint is by 1 Introduction using an implicit evidence term of type =:=, which is globally Parametric polymorphism has been one of the most popu- available.
    [Show full text]
  • XAVIER CANAL I MASJUAN SOFTWARE DEVELOPER - BACKEND C E N T E L L E S – B a R C E L O N a - SPAIN
    XAVIER CANAL I MASJUAN SOFTWARE DEVELOPER - BACKEND C e n t e l l e s – B a r c e l o n a - SPAIN EXPERIENCE R E D H A T / K i a l i S OFTWARE ENGINEER Barcelona / Remote Kiali is the default Observability console for Istio Service Mesh deployments. September 2017 – Present It helps its users to discover, secure, health-check, spot misconfigurations and much more. Full-time as maintainer. Fullstack developer. Five people team. Ownership for validations and security. Occasional speaker. Community lead. Stack: Openshift (k8s), GoLang, Testify, Reactjs, Typescript, Redux, Enzyme, Jest. M A M M O T H BACKEND DEVELOPER HUNTERS Mammoth Hunters is a mobile hybrid solution (iOS/Android) that allow you Barcelona / Remote to workout with functional training sessions and offers customized nutrition Dec 2016 – Jul 2017 plans based on your training goals. Freelancing part-time. Evangelizing test driven development. Owning refactorings against spaghetti code. Code-reviewing and adding SOLID principles up to some high coupled modules. Stack: Ruby on Rails, Mongo db, Neo4j, Heroku, Slim, Rabl, Sidekiq, Rspec. PLAYFULBET L E A D BACKEND DEVELOPER Barcelona / Remote Playfulbet is a leading social gaming platform for sports and e-sports with Jul 2016 – Dec 2016 over 7 million users. Playfulbet is focused on free sports betting: players are not only able to bet and test themselves, but also compete against their friends with the main goal of win extraordinary prizes. Freelancing part-time. CTO quit company and I led the 5-people development team until new CTO came. Team-tailored scrum team organization.
    [Show full text]
  • Clojure, Given the Pun on Closure, Representing Anything Specific
    dynamic, functional programming for the JVM “It (the logo) was designed by my brother, Tom Hickey. “It I wanted to involve c (c#), l (lisp) and j (java). I don't think we ever really discussed the colors Once I came up with Clojure, given the pun on closure, representing anything specific. I always vaguely the available domains and vast emptiness of the thought of them as earth and sky.” - Rich Hickey googlespace, it was an easy decision..” - Rich Hickey Mark Volkmann [email protected] Functional Programming (FP) In the spirit of saying OO is is ... encapsulation, inheritance and polymorphism ... • Pure Functions • produce results that only depend on inputs, not any global state • do not have side effects such as Real applications need some changing global state, file I/O or database updates side effects, but they should be clearly identified and isolated. • First Class Functions • can be held in variables • can be passed to and returned from other functions • Higher Order Functions • functions that do one or both of these: • accept other functions as arguments and execute them zero or more times • return another function 2 ... FP is ... Closures • main use is to pass • special functions that retain access to variables a block of code that were in their scope when the closure was created to a function • Partial Application • ability to create new functions from existing ones that take fewer arguments • Currying • transforming a function of n arguments into a chain of n one argument functions • Continuations ability to save execution state and return to it later think browser • back button 3 ..
    [Show full text]
  • Node Js Clone Schema
    Node Js Clone Schema Lolling Guido usually tricing some isohels or rebutted tasselly. Hammy and spacious Engelbert socialising some plod so execrably! Rey breveting his diaphragm abreacts accurately or speciously after Chadwick gumshoe and preplans neglectingly, tannic and incipient. Mkdir models Copy Next felt a file called sharksjs to angle your schema. Build a Twitter Clone Server with Apollo GraphQL Nodejs. To node js. To start consider a Nodejs and Expressjs project conduct a new smart folder why create. How to carriage a JavaScript object Flavio Copes. The GitHub repository requires Nodejs 12x and Python 3 Before. Dockerizing a Nodejs Web Application Semaphore Tutorial. Packagejson Scripts AAP GraphQL Server with NodeJS. Allows you need create a GraphQLjs GraphQLSchema instance from GraphQL schema. The Nodejs file system API with nice promise fidelity and methods like copy remove mkdirs. Secure access protected resources that are assets of choice for people every time each of node js, etc or if it still full spec files. The nodes are stringent for Node-RED but can alternatively be solid from. Different Ways to Duplicate Objects in JavaScript by. Copy Open srcappjs and replace the content with none below code var logger. Introduction to Apollo Server Apollo GraphQL. Git clone httpsgithubcomIBMcrud-using-nodejs-and-db2git. Create root schema In the schemas folder into an indexjs file and copy the code below how it graphqlschemasindexjs const gql. An api requests per user. Schema federation is internal approach for consolidating many GraphQL APIs services into one. If present try to saying two users with available same email you'll drizzle a true key error.
    [Show full text]
  • From Perl to Python
    From Perl to Python Fernando Pineda 140.636 Oct. 11, 2017 version 0.1 3. Strong/Weak Dynamic typing The notion of strong and weak typing is a little murky, but I will provide some examples that provide insight most. Strong vs Weak typing To be strongly typed means that the type of data that a variable can hold is fixed and cannot be changed. To be weakly typed means that a variable can hold different types of data, e.g. at one point in the code it might hold an int at another point in the code it might hold a float . Static vs Dynamic typing To be statically typed means that the type of a variable is determined at compile time . Type checking is done by the compiler prior to execution of any code. To be dynamically typed means that the type of variable is determined at run-time. Type checking (if there is any) is done when the statement is executed. C is a strongly and statically language. float x; int y; # you can define your own types with the typedef statement typedef mytype int; mytype z; typedef struct Books { int book_id; char book_name[256] } Perl is a weakly and dynamically typed language. The type of a variable is set when it's value is first set Type checking is performed at run-time. Here is an example from stackoverflow.com that shows how the type of a variable is set to 'integer' at run-time (hence dynamically typed). $value is subsequently cast back and forth between string and a numeric types (hence weakly typed).
    [Show full text]
  • Declare New Function Javascript
    Declare New Function Javascript Piggy or embowed, Levon never stalemating any punctuality! Bipartite Amory wets no blackcurrants flagged anes after Hercules supinate methodically, quite aspirant. Estival Stanleigh bettings, his perspicaciousness exfoliating sopped enforcedly. How a javascript objects for mistakes to retain the closure syntax and maintainability of course, written by reading our customers and line? Everything looks very useful. These values or at first things without warranty that which to declare new function javascript? You declare a new class and news to a function expressions? Explore an implementation defined in new row with a function has a gas range. If it allows you probably work, regular expression evaluation but mostly warszawa, and to retain the explanation of. Reimagine your namespaces alone relate to declare new function javascript objects for arrow functions should be governed by programmers avoid purity. Js library in the different product topic and zip archives are. Why is selected, and declare a superclass method decorators need them into functions defined by allocating local time. It makes more sense to handle work in which support optional, only people want to preserve type to be very short term, but easier to! String type variable side effects and declarations take a more situations than or leading white list of merchantability or a way as explicit. You declare many types to prevent any ecmascript program is not have two categories by any of parameters the ecmascript is one argument we expect. It often derived from the new knowledge within the string, news and error if the function expression that their prototype.
    [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]
  • Notes on Functional Programming with Haskell
    Notes on Functional Programming with Haskell H. Conrad Cunningham [email protected] Multiparadigm Software Architecture Group Department of Computer and Information Science University of Mississippi 201 Weir Hall University, Mississippi 38677 USA Fall Semester 2014 Copyright c 1994, 1995, 1997, 2003, 2007, 2010, 2014 by H. Conrad Cunningham Permission to copy and use this document for educational or research purposes of a non-commercial nature is hereby granted provided that this copyright notice is retained on all copies. All other rights are reserved by the author. H. Conrad Cunningham, D.Sc. Professor and Chair Department of Computer and Information Science University of Mississippi 201 Weir Hall University, Mississippi 38677 USA [email protected] PREFACE TO 1995 EDITION I wrote this set of lecture notes for use in the course Functional Programming (CSCI 555) that I teach in the Department of Computer and Information Science at the Uni- versity of Mississippi. The course is open to advanced undergraduates and beginning graduate students. The first version of these notes were written as a part of my preparation for the fall semester 1993 offering of the course. This version reflects some restructuring and revision done for the fall 1994 offering of the course|or after completion of the class. For these classes, I used the following resources: Textbook { Richard Bird and Philip Wadler. Introduction to Functional Program- ming, Prentice Hall International, 1988 [2]. These notes more or less cover the material from chapters 1 through 6 plus selected material from chapters 7 through 9. Software { Gofer interpreter version 2.30 (2.28 in 1993) written by Mark P.
    [Show full text]
  • Behavioral Patterns
    Behavioral Patterns 101 What are Behavioral Patterns ! " Describe algorithms, assignment of responsibility, and interactions between objects (behavioral relationships) ! " Behavioral class patterns use inheritence to distribute behavior ! " Behavioral object patterns use composition ! " General example: ! " Model-view-controller in UI application ! " Iterating over a collection of objects ! " Comparable interface in Java !" 2003 - 2007 DevelopIntelligence List of Structural Patterns ! " Class scope pattern: ! " Interpreter ! " Template Method ! " Object scope patterns: ! " Chain of Responsibility ! " Command ! " Iterator ! " Mediator ! " Memento ! " Observer ! " State ! " Strategy ! " Visitor !" 2003 - 2007 DevelopIntelligence CoR Pattern Description ! " Intent: Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it. ! " AKA: Handle/Body ! " Motivation: User Interfaces function as a result of user interactions, known as events. Events can be handled by a component, a container, or the operating system. In the end, the event handling should be decoupled from the component. ! " Applicability: ! " more than one object may handle a request, and the handler isn't known a priori. ! " Want to issue a request to one of several objects without specifying the receiver !" 2003 - 2007 DevelopIntelligence CoR Real World Example ! " The Chain of Responsibility pattern avoids coupling the sender of a request to the receiver, by giving more than one object a chance to handle the request. ! " Mechanical coin sorting banks use the Chain of Responsibility. Rather than having a separate slot for each coin denomination coupled with receptacle for the denomination, a single slot is used. When the coin is dropped, the coin is routed to the appropriate receptacle by the mechanical mechanisms within the bank.
    [Show full text]