INTRODUCTION. SHORT INTRODUCTION TO SCALA INGEGNERIA DEL SOFTWARE Università degli Studi di Padova

Size: px
Start display at page:

Download "INTRODUCTION. SHORT INTRODUCTION TO SCALA INGEGNERIA DEL SOFTWARE Università degli Studi di Padova"

Transcription

1 SHORT INTRODUCTION TO SCALA INGEGNERIA DEL SOFTWARE Università degli Studi di Padova Dipartimento di Matematica Corso di Laurea in Informatica, A.A INTRODUCTION Object/functional programming language Based on Java Virtual Machine Full interoperability with Java libraries Pure object orientation (no primitive types) Every function is a value High order functions (lambdas) Promoting immutability Currying Pattern matching Statically typed Intelligent type system Extensible 2003: internal use to EPFL 2004: version : version : the «growth year» 2014: version 2.11 (JVM 8) 2 INTRODUCTION Language main features Read Eval Print Loop (REPL) interpreter An interactive shell to execute statements "on the fly" Variables UML syntax > name : type val x: Int = Immutable lazy val x: Int = Immutable and lazy var x: Int = Mutable def x: Int = Executed every time Very smart type inferer val x = 1 x: Int No semicolon Blocks, blocks everywhere... INTRODUCTION Language main features Every statement is a "pure" expression No return statement needed! The if-else statement is a value val y = 4 // x has type String val x = if (y < 3) "minor" else "greater" Imperative for statement is not supported Use the for-yield statement instead // Returns an array of integers between 2 and 101 for (i <- (1 to 100)) yield i + 1 Every char can be used to define names (%$#@?...) 3 4

2 Everything is an object Classes Values class Person(val name: String, val surname: String, val birth: Date) { // Main Ctor body here References (Scala and Java) // Every secondary Ctor must call the main Ctor as // first statement (very restrictive) def this(name: String) = this(name, "", null) def age(): Int = { /* return the age */ // Override intention must be declared override def tostring = s"my name is $name $surname" 5 6 Classes Main constructor is declared within Class name Ctor body is made of statements in class body Accessor methods are build automatically val immutable value, getter only var mutable value, getter and setter def defines methods (and functions too...) Use equal "=" iff the method is a function No public class You can have more than a class into a.scala file No static methods (wait a minute...)...so let s introduce objects notation! 7 8

3 Object Native Singleton pattern implementation object ChuckNorris extends Person("Chuck Norris") { // This is a static method def roundhousekick = "Roundhouse" println ChuckNorris.roundhouseKick There can be only one instance of ChuckNorris Companion object An object called as an existing class Companion object s methods are static method of the class class Person(val name: String, val surname: String) object Person { // Companion object def somestupidstaticmethod = "This is a static method" println Person.someStupidStaticMethod 9 Object Companion objects implement also Factory Method pattern natively Every apply method creates an instance of the class Syntactic sugar: Class.apply(...) Class(...) It s like a class application (...function anyone?) class Person(val name: String, val surname: String) object Person { // Factory method def apply(n: String, s: String) = new Person(n, s) // Application of the class will return a new instance val ricky = Person("Riccardo", "Cardin") // No new operator There can be more than one apply!!!! 10 Object Used also to define the entry point of an application The Java way Abstract classes Also defines a main constructor It has to be called from the derived classes main Ctor object Hello { // Every object containing a main method could be // Executed. There are no restriction on file name def main(args: Array[String]) { println("hello World!") The Scala way object Hello extends App { // All the code in the object s ctor body will be // executed as our application. // Arguments are accessible via an args variable, // available in the App trait println("hello World!") abstract class Animal(val species: String) { def walk // Abstract method class Person(val name: String, val surname: String) // Calling main ctor directly in class // definition extends Animal("Human") { def walk = { /* Do some stuff */ val ricky = new Person("Riccardo", "Cardin") 11 12

4 Traits: interfaces or abstract classes? Like interfaces, they have not a constructor To implement a single trait, use extends Otherwise, use with (mixin) But, they can have methods with implementation and attributes Similar (but more powerful) to default methods in Java 8 Multiple inheritance problem trait A { override def tostring = "I m A" trait B { override def tostring = "I m B" trait C { override def tostring = "I m C" class D extends A with B, C new D().toString // Prints I m C Class linearization: use the rightmost type (more or less...) Traits Like an interface // No implementation at all trait Sorter { def sort(list: List[Int]): List[Int] class QuickSorter extends Sorter { def sort(list: List[Int]) = { /* Do something */ Like an abstract class trait AbstractDao { // No Ctor (wtf!) var pool: Array[Datasource] def getpool = pool // Implemented method def save // abstract method def delete // abstract method class UserDao extends AbstractDao { // Has to implement save and delete Traits Inside a mixin the super refers to the previuos trait in the linearized type Used to implement the Decorator pattern natively trait Employee { //... def whois(): String class Engineer(name: String, office: String) extends Employee trait ProjectManager extends Employee { abstract override def whois() { // super refers to the previuos trait on the left super.whois(buffer) println("and I am a project manager too!") new Engineer("Riccardo","Development") with ProjectManager Statically binded Decorator pattern Traits and Objects Using the companion object of a trait, we can implement the Abstract Factory pattern // Abstract factory trait AbstractFactory // Private classes scope is limited to the // definition file private class ConcreteFactory1 extends AbstractFactory { /*... */ private class ConcreteFactory2 extends AbstractFactory { /*... */ object AbstractFactory{ def apply(kind: String) = kind match { case factory1" => new ConcreteFactory1 () case factory2" => new ConcreteFactory1 () factory 2 val factory = AbstractFactory("factory1") 15 16

5 Case classes and pattern matching Scala has a built in pattern matching mechanism def matchtest(x: Int): String = x match { case 1 => "one" case _ => "many" println(matchtest(3)) // Prints many Case class: regular class that can be pattern matched Turns all ctor params into val (immutable) constants Generates a companion object w/ apply methods Generates tostring, equals and hashcode methods properly Checks the equality among attributes Case clauses are evaulated from top to bottom trait Term case class Var(name: String) extends Term case class Fun(arg: String, body: Term) extends Term Var("x") == Var("x") // Prints true Case classes and pattern matching Native implementation of Value Object pattern Obviously, case classes can be used in pattern matching... The match is done recursively on the structure of the type trait Term case class Var(name: String) extends Term case class Fun(arg: String, body: Term) extends Term def printterm(term: Term) { term match { // The clauses uses placeholders for variables. // If we don t need the value, we can use Var(_) case Var(n) => print( We have a variable! ) case Fun(x, b) => print( We have a function! ) MISCELLANEA MISCELLANEA Generics: more or less like Java Generics Subtyping of generic types is "invariant" class Node[T](elem: T) val node = new Node(3) // Smart type inference...but it can also be used in a variant (+T) o contravariant (-T) fashion There are also upper type bound (T<:A) and lower type bound (T>:A) case class ListNode[+T](h: T, t: ListNode[T]) { def head: T = h def tail: ListNode[T] = t def prepend[u >: T](elem: U): ListNode[U] = ListNode(elem, this) Option[A] type A list with zero (None) or one element (Some[A]) Native implementation of the Null Object Pattern No more NullPointerExceptions!! trait Option[T] { def isdefined: Boolean def get: T // Throws an exception if None def getorelse(t: T): T case class Some[T](elem: T) extends Option[T] case object None extends Option[Nothing] Use them with pattern matching: results garanted! def negate(x: Option[Int]) = x match { case None => throw new IllegalArgumentException case Some(i) => -i 19 20

6 MISCELLANEA Implicit classes Used to translate object between similar types i.e, from Java types (int) to Scala type (Int) Native implementation of Adapter pattern! trait Log { def warning(message: String) def error(message: String) The main ctor is used to final class Logger { def log(level: Level, message: String) { /*... */ resolve the conversion implicit class LoggerToLogAdapter(logger: Logger) extends Log { def warning(message: String) { logger.log(warning, message) def error(message: String) { logger.log(error, message) // The instance of Logger is translated to an instance of Log val log: Log = new Logger() MISCELLANEA Tuples Have you ever want a simple couple of value container, while you were programming in Java? Scala has a type, Tuples, that is just a tuple of values Don t abuse of it: remember that things called classes? Used internally by the compilator to treat function s arguments You can build tuples with «up to 22» values val things = ("a", 1, 3.5) // (java.lang.string, Int, Double) println(things._1) // Prints a println(things._2) // Prints 1 // Create a tuple using the -> operator val tuple = 1 -> "a" // (Int, java.lang.string) FP, a "new" programming paradigm Not so young, instead Lambda calculus Lisp Main principles Functions are high order, first class citizen Refer to it, pass as argument to another function Pure function No side effects, immutability (referential transparency) Recursion Haskell Scala Clojure 23 24

7 Functions: first class citizens def name (parameters-list)[: return-type] parameters-list := name: type Functions are compiled into object of an anonymous class extending a trait FunctionX X represents the number of parameters abstract def apply(v1: T1, v2: T2, ): R Strategy Pattern anyone? Definizione val max = (x: Int, y: Int) => if (x < y) y else x // Compiler builds an anonimous class, extending the trait // FunctionX, where X is the number of parameters val anonfun2 = new Function2[Int, Int, Int] { // Application method, as in companion objects def apply(x: Int, y: Int): Int = if (x < y) y else x assert(max(0, 1) == anonfun2(0, 1)) Functions (a.k.a. lambdas) // Complete definition def hello1(s: String): String = Hello + s // Inferred return type def hello2(s: String) = Hello + s // Using function literal def hello3 = (s: String) => Hello + s // Assigning a function to another function, inferred type def hello4 = hello3 // copy of definition //...or assigning a function to a val val hello5 = hello4 // as val (no difference, unless...) // Assigning a function to another function, not inferred type def hello6: String => String = hello1 // For every param it can be use the wildcard _ if it is used only // one time in the function body def hello: String => String = "Hello " + _ Return clause is redundant: last expression of the function body is the value returned Recursion Let s try to define the factorial function // Simple recursion def factorial(n: Int): Int = if (n == 0) 1 else n * factorial(n 1) Every step depends on the local variable n and on a recursive call of the function Every recursion step allocates a new frame in the stack Simple recursion StackOverflowError stack: n * f(n 1) n * f(n 2) n * f(n 3) n * f(n 4)

8 Recursion We need to limit the use of the stack: tail recursion // Tail recursion def factorial(n: Int): Int = def factacc(n: Int, acc: Int): Int = if (n == 0) acc else fastacc(n 1, acc * n) // Initial call fastacc(n) Every step depends only on the variables stored in the current stack frame Stack frame can be Tells Scala compiler to optimize the execution using a while loop We need an accumulator variable Currying Translation of the evaluation of a function that takes multiple arguments into a sequence of function, each with a single argument (partial application) f: (A, B) => C, than curry(f) = f c : A => (B => C) Used to abstract functions, separating the configuration of a function from its inputs // Let s generalize functions on sequence of integers def aggregate(id: Int, op: (Int, Int) => Int)(n: Int): Int = if (n == 0) id else op(aggregate(neutral, op)(n-1), n) // Factorial of integers from n to 0 def factorial = aggregate(1, _ * _)_ // Summing integers from n to 0 def sum = aggregate(0, _ + _)_ Do you know Haskell Curry? Can you see the application of the Template Method pattern? Call by value / name Using the call by value default approach, each function s argument is evaluated immediatly // Call by value def firstnonzero(a: Int, b: Int) = if (a!= 0) a else b println(firstnonzero(1, 3)) // Prints 1 def z(): Int = z() // Non terminating function println(firstnonzero(1, z)) // Non terminating function Scala implements also the call by name approach Arguments are evatuated only when needed This could lead to multiple evatualtion Try to have a look to streams... // Call by name def firstnonzerobyname(a: Int, b: => Int) = if (a!= 0) a else b println(firstnonzerobyname(1, z)) // Prints 1 First order function and call by name What if you want to implement the Command pattern, saving the commands history? object Invoker { // Sequence of executed commands private var history: Seq[() => Unit] = Seq.empty // Using call by name approach, to store the function // inside history w/out executing it def invoke(command: => Unit) { command history :+= command _ Invoker.invoke(println("foo")) Invoker.invoke { println("bar 1") println("bar 2") // At this point, history contains to functions 31 32

9 CONCLUSION And much more... Scala has a very good Collection framework Immutability and recursion foreach, filter, map, flatmap, foldleft,... Streams: infinite sequence of values Actors model Monads RIFERIMENTI Functional Programming Principles in Scala (Coursera) Scala School! Scala for the Impatient, Cay Horstmann, Addison Wesley The Evolution of Scala, Martin Odersky evolution Design Patterns in Scala in scala/ 35

Scala : an LLVM-targeted Scala compiler

Scala : an LLVM-targeted Scala compiler Scala : an LLVM-targeted Scala compiler Da Liu, UNI: dl2997 Contents 1 Background 1 2 Introduction 1 3 Project Design 1 4 Language Prototype Features 2 4.1 Language Features........................................

More information

n n Official Scala website n Scala API n

n   n Official Scala website n Scala API n n Quiz 8 Announcements n Rainbow grades: HW1-8, Quiz1-6, Exam1-2 n Still grading: HW9, Quiz 7 Scala n HW10 due today n HW11 out today, due Friday Fall 18 CSCI 4430, A Milanova 1 Today s Lecture Outline

More information

G Programming Languages - Fall 2012

G Programming Languages - Fall 2012 G22.2110-003 Programming Languages - Fall 2012 Week 13 - Part 1 Thomas Wies New York University Review Last lecture Object Oriented Programming Outline Today: Scala Sources: Programming in Scala, Second

More information

...something useful to do with the JVM.

...something useful to do with the JVM. Scala Finally... ...something useful to do with the JVM. Image source: http://www.tripadvisor.com/locationphotos-g187789-lazio.html Young Developed in 2003 by Martin Odersky at EPFL Martin also brought

More information

Programming in Scala Second Edition

Programming in Scala Second Edition Programming in Scala Second Edition Martin Odersky, Lex Spoon, Bill Venners artima ARTIMA PRESS WALNUT CREEK, CALIFORNIA Contents Contents List of Figures List of Tables List of Listings Foreword Foreword

More information

CS 2340 Objects and Design - Scala

CS 2340 Objects and Design - Scala CS 2340 Objects and Design - Scala Objects and Operators Christopher Simpkins chris.simpkins@gatech.edu Chris Simpkins (Georgia Tech) CS 2340 Objects and Design - Scala Objects and Operators 1 / 13 Classes

More information

Scala. Fernando Medeiros Tomás Paim

Scala. Fernando Medeiros Tomás Paim Scala Fernando Medeiros fernfreire@gmail.com Tomás Paim tomasbmp@gmail.com Topics A Scalable Language Classes and Objects Basic Types Functions and Closures Composition and Inheritance Scala s Hierarchy

More information

Refactoring to Functional. Hadi Hariri

Refactoring to Functional. Hadi Hariri Refactoring to Functional Hadi Hariri Functional Programming In computer science, functional programming is a programming paradigm, a style of building the structure and elements of computer programs,

More information

CPL 2016, week 10. Clojure functional core. Oleg Batrashev. April 11, Institute of Computer Science, Tartu, Estonia

CPL 2016, week 10. Clojure functional core. Oleg Batrashev. April 11, Institute of Computer Science, Tartu, Estonia CPL 2016, week 10 Clojure functional core Oleg Batrashev Institute of Computer Science, Tartu, Estonia April 11, 2016 Overview Today Clojure language core Next weeks Immutable data structures Clojure simple

More information

Scala, Your Next Programming Language

Scala, Your Next Programming Language Scala, Your Next Programming Language (or if it is good enough for Twitter, it is good enough for me) WORLDCOMP 2011 By Dr. Mark C. Lewis Trinity University Disclaimer I am writing a Scala textbook that

More information

Advanced Object-Oriented Languages Scala

Advanced Object-Oriented Languages Scala Advanced Object-Oriented Languages Scala Programming Paradigms Department of Computer Science University of Aalborg, Denmark Erik Ernst (U. of Aarhus) Overview Purpose of using Scala Introduction syntax

More information

Practically Functional. Daniel Spiewak

Practically Functional. Daniel Spiewak Practically Functional Daniel Spiewak whoami Author of Scala for Java Refugees and other articles on Scala and FP Former editor Javalobby / EclipseZone Engaged in academic research involving Scala DSLs

More information

Notes from a Short Introductory Lecture on Scala (Based on Programming in Scala, 2nd Ed.)

Notes from a Short Introductory Lecture on Scala (Based on Programming in Scala, 2nd Ed.) Notes from a Short Introductory Lecture on Scala (Based on Programming in Scala, 2nd Ed.) David Haraburda January 30, 2013 1 Introduction Scala is a multi-paradigm language that runs on the JVM (is totally

More information

A Whirlwind Tour of Scala. Kevin Kilroy October 2014

A Whirlwind Tour of Scala. Kevin Kilroy October 2014 A Whirlwind Tour of Scala Kevin Kilroy October 2014 A Brief History of Scala... Created in 2001 by javac author 1995 created Pizza with 1998 created GJ with 1999 Joined EPFL Created Funnel 2001 Scala 2003

More information

Programming Kotlin. Familiarize yourself with all of Kotlin s features with this in-depth guide. Stephen Samuel Stefan Bocutiu BIRMINGHAM - MUMBAI

Programming Kotlin. Familiarize yourself with all of Kotlin s features with this in-depth guide. Stephen Samuel Stefan Bocutiu BIRMINGHAM - MUMBAI Programming Kotlin Familiarize yourself with all of Kotlin s features with this in-depth guide Stephen Samuel Stefan Bocutiu BIRMINGHAM - MUMBAI Programming Kotlin Copyright 2017 Packt Publishing First

More information

Announcements. CSCI 334: Principles of Programming Languages. Lecture 16: Intro to Scala. Announcements. Squeak demo. Instructor: Dan Barowy

Announcements. CSCI 334: Principles of Programming Languages. Lecture 16: Intro to Scala. Announcements. Squeak demo. Instructor: Dan Barowy Announcements CSCI 334: Principles of Programming Languages Lecture 16: Intro to Scala HW7 sent out as promised. See course webpage. Instructor: Dan Barowy Announcements No class on Tuesday, April 17.

More information

JVM ByteCode Interpreter

JVM ByteCode Interpreter JVM ByteCode Interpreter written in Haskell (In under 1000 Lines of Code) By Louis Jenkins Presentation Schedule ( 15 Minutes) Discuss and Run the Virtual Machine first

More information

Introduction to Scala

Introduction to Scala The new Java? July 4, 2009 Presentation Outline Outline Introduction Concise Syntax Object Orientation Functional Programming Various Stuff Conclusion Introducing Scala What is Scala? 100% Object-oriented

More information

COP4020 Programming Languages. Functional Programming Prof. Robert van Engelen

COP4020 Programming Languages. Functional Programming Prof. Robert van Engelen COP4020 Programming Languages Functional Programming Prof. Robert van Engelen Overview What is functional programming? Historical origins of functional programming Functional programming today Concepts

More information

ASSERTIONS AND LOGGING

ASSERTIONS AND LOGGING SUMMARY Exception handling, ASSERTIONS AND LOGGING PROGRAMMAZIONE CONCORRENTE E DISTR. Università degli Studi di Padova Dipartimento di Matematica Corso di Laurea in Informatica, A.A. 2015 2016 rcardin@math.unipd.it

More information

Functional Programming and Haskell

Functional Programming and Haskell Functional Programming and Haskell Tim Dawborn University of Sydney, Australia School of Information Technologies Tim Dawborn Functional Programming and Haskell 1/22 What are Programming Paradigms? A programming

More information

Object-oriented programming

Object-oriented programming Object-oriented programming HelloWorld The following code print Hello World on the console object HelloWorld { def main(args: Array[String]): Unit = { println("hello World") 2 1 object The keyword object

More information

Optimizing Higher-Order Functions in Scala

Optimizing Higher-Order Functions in Scala Optimizing Higher-Order Functions in Scala Iulian Dragos EPFL Outline A quick tour of Scala Generalities Extension through libraries Closure translation in Scala Cost Optimizations in the Scala compiler

More information

Functional programming in C#

Functional programming in C# Functional programming in C# A quick approach to another paradigm Nacho Iborra IES San Vicente This work is licensed under the Creative Commons Attribution- NonCommercial-ShareAlike 4.0 International License.

More information

CSCI-GA Scripting Languages

CSCI-GA Scripting Languages CSCI-GA.3033.003 Scripting Languages 12/02/2013 OCaml 1 Acknowledgement The material on these slides is based on notes provided by Dexter Kozen. 2 About OCaml A functional programming language All computation

More information

Bibliography. Analyse et Conception Formelle. Lesson 5. Crash Course on Scala. Scala in a nutshell. Outline

Bibliography. Analyse et Conception Formelle. Lesson 5. Crash Course on Scala. Scala in a nutshell. Outline Bibliography Analyse et Conception Formelle Lesson 5 Crash Course on Scala Simply Scala. Onlinetutorial: http://www.simply.com/fr http://www.simply.com/ Programming in Scala, M. Odersky, L. Spoon, B. Venners.

More information

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Weiss Chapter 1 terminology (parenthesized numbers are page numbers) Weiss Chapter 1 terminology (parenthesized numbers are page numbers) assignment operators In Java, used to alter the value of a variable. These operators include =, +=, -=, *=, and /=. (9) autoincrement

More information

First Programming Language in CS Education The Arguments for Scala

First Programming Language in CS Education The Arguments for Scala First Programming Language in CS Education The Arguments for Scala WORLDCOMP 2011 By Dr. Mark C. Lewis Trinity University Disclaimer I am writing a Scala textbook that is under contract with CRC Press.

More information

Lecture 8: Summary of Haskell course + Type Level Programming

Lecture 8: Summary of Haskell course + Type Level Programming Lecture 8: Summary of Haskell course + Type Level Programming Søren Haagerup Department of Mathematics and Computer Science University of Southern Denmark, Odense October 31, 2017 Principles from Haskell

More information

Arne Brüsch Philipp Wille. Pattern Matching Syntax

Arne Brüsch Philipp Wille. Pattern Matching Syntax Scala Enthusiasts BS Arne Brüsch Philipp Wille Pattern Matching Syntax Scala Modular programming language Some used to call it objectfunctional 2 Scala Modular programming language Some used to call it

More information

Topic VIII. The state of the art Scala < > Scala By Example by M. Odersky. Programming Methods Laboratory, EPFL, 2008.

Topic VIII. The state of the art Scala <  > Scala By Example by M. Odersky. Programming Methods Laboratory, EPFL, 2008. References: Topic VIII The state of the art Scala < www.scala-lang.org > Scala By Example by M. Odersky. Programming Methods Laboratory, EPFL, 2008. An overview of the Scala programming language by M.

More information

Lecture 09: Introduction to Scala

Lecture 09: Introduction to Scala Lecture 09: Introduction to Scala Computer Science Department, University of Crete Multicore Processor Programming Based on slides by D. Malayeri, S.D. Vick, P. Haller, and M. Madsen Pratikakis (CSD) Scala

More information

Using Scala for building DSL s

Using Scala for building DSL s Using Scala for building DSL s Abhijit Sharma Innovation Lab, BMC Software 1 What is a DSL? Domain Specific Language Appropriate abstraction level for domain - uses precise concepts and semantics of domain

More information

Programs as Data. The Scala language

Programs as Data. The Scala language Programs as Data The Scala language Peter Sestoft 2011-11-14 1 Agenda Kursusevaluering slutter i dag! Object-oriented programming in Scala Classes Singletons (object) Traits Compiling and running Scala

More information

CS 11 Haskell track: lecture 1

CS 11 Haskell track: lecture 1 CS 11 Haskell track: lecture 1 This week: Introduction/motivation/pep talk Basics of Haskell Prerequisite Knowledge of basic functional programming e.g. Scheme, Ocaml, Erlang CS 1, CS 4 "permission of

More information

CS558 Programming Languages

CS558 Programming Languages CS558 Programming Languages Fall 2016 Lecture 6a Andrew Tolmach Portland State University 1994-2016 Functional Programming An alternative paradigm to imperative programming First-class functions Emphasis

More information

Kotlin, Start? Start! (pluu) Android Developer GDG Korea Android Organizer

Kotlin, Start? Start! (pluu) Android Developer GDG Korea Android Organizer Kotlin, Start? Start! (pluu) Android Developer GDG Korea Android Organizer Agenda Kotlin Overview Kotlin?? Basic fun main(args: Array): Unit { println("hello, world!") Basic Function Keyword

More information

Functional Programming. Pure Functional Languages

Functional Programming. Pure Functional Languages Functional Programming Pure functional PLs S-expressions cons, car, cdr Defining functions read-eval-print loop of Lisp interpreter Examples of recursive functions Shallow, deep Equality testing 1 Pure

More information

Chapter 1. Fundamentals of Higher Order Programming

Chapter 1. Fundamentals of Higher Order Programming Chapter 1 Fundamentals of Higher Order Programming 1 The Elements of Programming Any powerful language features: so does Scheme primitive data procedures combinations abstraction We will see that Scheme

More information

Using Scala in CS241

Using Scala in CS241 Using Scala in CS241 Winter 2018 Contents 1 Purpose 1 2 Scala 1 3 Basic Syntax 2 4 Tuples, Arrays, Lists and Vectors in Scala 3 5 Binary output in Scala 5 6 Maps 5 7 Option types 5 8 Objects and Classes

More information

CS162 Week 1. Kyle Dewey. Friday, January 10, 14

CS162 Week 1. Kyle Dewey. Friday, January 10, 14 CS162 Week 1 Kyle Dewey Overview Basic Introduction CS Accounts Scala survival guide Office Hour Choose an hour from within: Tuesday/Thursday 11 AM - 1 PM Friday 11 AM - 4 PM Also available by appointment

More information

Index COPYRIGHTED MATERIAL

Index COPYRIGHTED MATERIAL Index COPYRIGHTED MATERIAL Note to the Reader: Throughout this index boldfaced page numbers indicate primary discussions of a topic. Italicized page numbers indicate illustrations. A abstract classes

More information

The SCAlable LAnguage

The SCAlable LAnguage The SCAlable LAnguage The Scala Language: Object Oriented Functional Programming Gabor Szokoli Overview Introduction Everything is an Object Inheritance and mixins For comprehensions Generic Types: Covariance,

More information

Scala. ~ a tragedy in two parts ~ the tragedy being we aren t using it all the time

Scala. ~ a tragedy in two parts ~ the tragedy being we aren t using it all the time e Scala ~ a tragedy in two parts ~ the tragedy being we aren t using it all the time w g I The Scala Language Praise for Scala j s gi can honestly say if someone had shown me the Programming in Scala...

More information

n n Try tutorial on front page to get started! n spring13/ n Stack Overflow!

n   n Try tutorial on front page to get started! n   spring13/ n Stack Overflow! Announcements n Rainbow grades: HW1-6, Quiz1-5, Exam1 n Still grading: HW7, Quiz6, Exam2 Intro to Haskell n HW8 due today n HW9, Haskell, out tonight, due Nov. 16 th n Individual assignment n Start early!

More information

Functions, Closures and Control Abstraction

Functions, Closures and Control Abstraction Functions, Closures and Control Abstraction Christopher Simpkins csimpkin@spsu.edu CS 3693, Fall 2011 Chris Simpkins (Georgia Tech) CS 3693 Scala 2011-09-07 1 / 1 Aside: drop and take (Optional) homework:

More information

Scala - Some essential concepts -

Scala - Some essential concepts - Scala - Some essential concepts - Marcel Lüthi Graphics and Vision Research Group Department of Mathematics and Computer Science University of Basel Programming an important activity Data preprocessing

More information

High-level Parallel Programming: Scala on the JVM

High-level Parallel Programming: Scala on the JVM High-level Parallel Programming: Scala on the JVM Contents of Lecture 4 The Scala programming language Parallel programming using actors Jonas Skeppstedt (jonasskeppstedt.net) Lecture 4 2017 1 / 40 Purpose

More information

Topics Covered Thus Far. CMSC 330: Organization of Programming Languages. Language Features Covered Thus Far. Programming Languages Revisited

Topics Covered Thus Far. CMSC 330: Organization of Programming Languages. Language Features Covered Thus Far. Programming Languages Revisited CMSC 330: Organization of Programming Languages Type Systems, Names & Binding Topics Covered Thus Far Programming languages Syntax specification Regular expressions Context free grammars Implementation

More information

Overview. Elements of Programming Languages. Evaluation order. Evaluation order

Overview. Elements of Programming Languages. Evaluation order. Evaluation order Overview Elements of Programming Languages Lecture 15: Evaluation strategies and laziness James Cheney University of Edinburgh November 18, 216 Final few lectures: cross-cutting language design issues

More information

Lecture 21: The Many Hats of Scala: OOP 10:00 AM, Mar 14, 2018

Lecture 21: The Many Hats of Scala: OOP 10:00 AM, Mar 14, 2018 CS18 Integrated Introduction to Computer Science Fisler, Nelson Lecture 21: The Many Hats of Scala: OOP 10:00 AM, Mar 14, 2018 Contents 1 Mutation in the Doghouse 1 1.1 Aside: Access Modifiers..................................

More information

CSCI-GA Final Exam

CSCI-GA Final Exam CSCI-GA 2110-003 - Final Exam Instructor: Thomas Wies Name: Sample Solution ID: You have 110 minutes time. There are 7 assignments and you can reach 110 points in total. You can solve the exercises directly

More information

Scheme. Functional Programming. Lambda Calculus. CSC 4101: Programming Languages 1. Textbook, Sections , 13.7

Scheme. Functional Programming. Lambda Calculus. CSC 4101: Programming Languages 1. Textbook, Sections , 13.7 Scheme Textbook, Sections 13.1 13.3, 13.7 1 Functional Programming Based on mathematical functions Take argument, return value Only function call, no assignment Functions are first-class values E.g., functions

More information

Classical Themes of Computer Science

Classical Themes of Computer Science Functional Programming (Part 1/2) Bernhard K. Aichernig Institute for Software Technology Graz University of Technology Austria Winter Term 2017/18 Version: November 22, 2017 1/49 Agenda I Functional Programming?

More information

3. Functional Programming. Oscar Nierstrasz

3. Functional Programming. Oscar Nierstrasz 3. Functional Programming Oscar Nierstrasz Roadmap > Functional vs. Imperative Programming > Pattern Matching > Referential Transparency > Lazy Evaluation > Recursion > Higher Order and Curried Functions

More information

1. true / false By a compiler we mean a program that translates to code that will run natively on some machine.

1. true / false By a compiler we mean a program that translates to code that will run natively on some machine. 1. true / false By a compiler we mean a program that translates to code that will run natively on some machine. 2. true / false ML can be compiled. 3. true / false FORTRAN can reasonably be considered

More information

What s different about Factor?

What s different about Factor? Harshal Lehri What s different about Factor? Factor is a concatenative programming language - A program can be viewed as a series of functions applied on data Factor is a stack oriented program - Data

More information

Subclass Gist Example: Chess Super Keyword Shadowing Overriding Why? L10 - Polymorphism and Abstract Classes The Four Principles of Object Oriented

Subclass Gist Example: Chess Super Keyword Shadowing Overriding Why? L10 - Polymorphism and Abstract Classes The Four Principles of Object Oriented Table of Contents L01 - Introduction L02 - Strings Some Examples Reserved Characters Operations Immutability Equality Wrappers and Primitives Boxing/Unboxing Boxing Unboxing Formatting L03 - Input and

More information

Topics Covered Thus Far CMSC 330: Organization of Programming Languages

Topics Covered Thus Far CMSC 330: Organization of Programming Languages Topics Covered Thus Far CMSC 330: Organization of Programming Languages Names & Binding, Type Systems Programming languages Ruby Ocaml Lambda calculus Syntax specification Regular expressions Context free

More information

CMSC 330: Organization of Programming Languages

CMSC 330: Organization of Programming Languages CMSC 330: Organization of Programming Languages Type Systems, Names and Binding CMSC 330 - Spring 2013 1 Topics Covered Thus Far! Programming languages Ruby OCaml! Syntax specification Regular expressions

More information

CS Programming Languages: Scala

CS Programming Languages: Scala CS 3101-2 - Programming Languages: Scala Lecture 3: Fun with Functions Daniel Bauer (bauer@cs.columbia.edu) October 29, 2014 Daniel Bauer CS3101-2 Scala - 03 - Fun with Functions 1/37 Contents 1 Defining

More information

CSCC24 Functional Programming Scheme Part 2

CSCC24 Functional Programming Scheme Part 2 CSCC24 Functional Programming Scheme Part 2 Carolyn MacLeod 1 winter 2012 1 Based on slides from Anya Tafliovich, and with many thanks to Gerald Penn and Prabhakar Ragde. 1 The Spirit of Lisp-like Languages

More information

CS 314 Principles of Programming Languages

CS 314 Principles of Programming Languages CS 314 Principles of Programming Languages Lecture 16: Functional Programming Zheng (Eddy Zhang Rutgers University April 2, 2018 Review: Computation Paradigms Functional: Composition of operations on data.

More information

CMSC330. Objects, Functional Programming, and lambda calculus

CMSC330. Objects, Functional Programming, and lambda calculus CMSC330 Objects, Functional Programming, and lambda calculus 1 OOP vs. FP Object-oriented programming (OOP) Computation as interactions between objects Objects encapsulate mutable data (state) Accessed

More information

LECTURE 16. Functional Programming

LECTURE 16. Functional Programming LECTURE 16 Functional Programming WHAT IS FUNCTIONAL PROGRAMMING? Functional programming defines the outputs of a program as a mathematical function of the inputs. Functional programming is a declarative

More information

Functional Programming Lecture 1: Introduction

Functional Programming Lecture 1: Introduction Functional Programming Lecture 1: Introduction Viliam Lisý Artificial Intelligence Center Department of Computer Science FEE, Czech Technical University in Prague viliam.lisy@fel.cvut.cz Acknowledgements

More information

According to Larry Wall (designer of PERL): a language by geniuses! for geniuses. Lecture 7: Haskell. Haskell 98. Haskell (cont) - Type-safe!

According to Larry Wall (designer of PERL): a language by geniuses! for geniuses. Lecture 7: Haskell. Haskell 98. Haskell (cont) - Type-safe! Lecture 7: Haskell CSC 131 Fall, 2014 Kim Bruce According to Larry Wall (designer of PERL): a language by geniuses for geniuses He s wrong at least about the latter part though you might agree when we

More information

Overview. Elements of Programming Languages. Advanced constructs. Motivating inner class example

Overview. Elements of Programming Languages. Advanced constructs. Motivating inner class example Overview Elements of Programming Languages Lecture 11: Object-oriented functional programming James Cheney University of Edinburgh October 30, 2017 We ve now covered: basics of functional programming (with

More information

Imperative languages

Imperative languages Imperative languages Von Neumann model: store with addressable locations machine code: effect achieved by changing contents of store locations instructions executed in sequence, flow of control altered

More information

Scala. Introduction. Scala

Scala. Introduction. Scala Scala Introduction 1 Scala Scala was proposed by Professor Martin Odersky and his group at EPFL in 2003 to provide a highperformance, concurrent-ready environment for functional programming and object-oriented

More information

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120) Programming Languages and Techniques () Lecture 20 February 28, 2018 Transition to Java Announcements HW05: GUI programming Due: THURSDAY!! at 11:59:59pm Lots of TA office hours today Thursday See Piazza

More information

.consulting.solutions.partnership. Clojure by Example. A practical introduction to Clojure on the JVM

.consulting.solutions.partnership. Clojure by Example. A practical introduction to Clojure on the JVM .consulting.solutions.partnership Clojure by Example A practical introduction to Clojure on the JVM Clojure By Example 1 Functional Progamming Concepts 3 2 Clojure Basics 4 3 Clojure Examples 5 4 References

More information

Introduction to Programming Using Java (98-388)

Introduction to Programming Using Java (98-388) Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;

More information

Functional Programming. Pure Functional Languages

Functional Programming. Pure Functional Languages Functional Programming Pure functional PLs S-expressions cons, car, cdr Defining functions read-eval-print loop of Lisp interpreter Examples of recursive functions Shallow, deep Equality testing 1 Pure

More information

Programming Systems in Artificial Intelligence Functional Programming

Programming Systems in Artificial Intelligence Functional Programming Click to add Text Programming Systems in Artificial Intelligence Functional Programming Siegfried Nijssen 8/03/16 Discover thediscover world at the Leiden world University at Leiden University Overview

More information

About the Tutorial. Audience. Prerequisites. Copyright & Disclaimer. Haskell Programming

About the Tutorial. Audience. Prerequisites. Copyright & Disclaimer. Haskell Programming About the Tutorial Haskell is a widely used purely functional language. Functional programming is based on mathematical functions. Besides Haskell, some of the other popular languages that follow Functional

More information

University of Tartu Faculty of Mathematics and Computer Science Institute of Computer Science

University of Tartu Faculty of Mathematics and Computer Science Institute of Computer Science University of Tartu Faculty of Mathematics and Computer Science Institute of Computer Science Martin Vels Concurrent programming languages: Scala Research paper for Distributed Systems Seminar Advisor:

More information

A LISP Interpreter in ML

A LISP Interpreter in ML UNIVERSITY OF OSLO Department of Informatics A LISP Interpreter in ML Mandatory Assignment 1 INF3110 September 21, 2009 Contents 1 1 Introduction The purpose of this assignment is to write an interpreter,

More information

Haske k ll An introduction to Functional functional programming using Haskell Purely Lazy Example: QuickSort in Java Example: QuickSort in Haskell

Haske k ll An introduction to Functional functional programming using Haskell Purely Lazy Example: QuickSort in Java Example: QuickSort in Haskell Haskell An introduction to functional programming using Haskell Anders Møller amoeller@cs.au.dk The most popular purely functional, lazy programming language Functional programming language : a program

More information

CS205: Scalable Software Systems

CS205: Scalable Software Systems CS205: Scalable Software Systems Lecture 4 September 14, 2016 Lecture 4 CS205: Scalable Software Systems September 14, 2016 1 / 16 Quick Recap Things covered so far Problem solving by recursive decomposition

More information

Introduction to Functional Programming in Haskell 1 / 56

Introduction to Functional Programming in Haskell 1 / 56 Introduction to Functional Programming in Haskell 1 / 56 Outline Why learn functional programming? The essence of functional programming What is a function? Equational reasoning First-order vs. higher-order

More information

Functional Programming

Functional Programming Functional Programming CS331 Chapter 14 Functional Programming Original functional language is LISP LISt Processing The list is the fundamental data structure Developed by John McCarthy in the 60 s Used

More information

An introduction introduction to functional functional programming programming using usin Haskell

An introduction introduction to functional functional programming programming using usin Haskell An introduction to functional programming using Haskell Anders Møller amoeller@cs.au.dkau Haskell The most popular p purely functional, lazy programming g language Functional programming language : a program

More information

Functional Programming. Pure Functional Programming

Functional Programming. Pure Functional Programming Functional Programming Pure Functional Programming Computation is largely performed by applying functions to values. The value of an expression depends only on the values of its sub-expressions (if any).

More information

Harvard School of Engineering and Applied Sciences CS 152: Programming Languages

Harvard School of Engineering and Applied Sciences CS 152: Programming Languages Harvard School of Engineering and Applied Sciences CS 152: Programming Languages Lecture 18 Thursday, March 29, 2018 In abstract algebra, algebraic structures are defined by a set of elements and operations

More information

The Young Person's Guide to zkl. The Young Person's Guide to zkl

The Young Person's Guide to zkl. The Young Person's Guide to zkl The Young Person's Guide to zkl The Young Person's Guide to zkl zkl doesn't attempt to boil the ocean, zkl doesn't want to warm the ocean. zkl wants to make a nice cup of tea. --Zander Kale zkl 1 is a

More information

Swift. Introducing swift. Thomas Woodfin

Swift. Introducing swift. Thomas Woodfin Swift Introducing swift Thomas Woodfin Content Swift benefits Programming language Development Guidelines Swift benefits What is Swift Benefits What is Swift New programming language for ios and OS X Development

More information

Control Structures. Christopher Simpkins CS 3693, Fall Chris Simpkins (Georgia Tech) CS 3693 Scala / 1

Control Structures. Christopher Simpkins CS 3693, Fall Chris Simpkins (Georgia Tech) CS 3693 Scala / 1 Control Structures Christopher Simpkins csimpkin@spsu.edu CS 3693, Fall 2011 Chris Simpkins (Georgia Tech) CS 3693 Scala 2011-08-31 1 / 1 Control Structures Scala has only four built-in control structures:

More information

Chapter 15. Functional Programming Languages

Chapter 15. Functional Programming Languages Chapter 15 Functional Programming Languages Copyright 2009 Addison-Wesley. All rights reserved. 1-2 Chapter 15 Topics Introduction Mathematical Functions Fundamentals of Functional Programming Languages

More information

Functional programming

Functional programming Functional programming Functional programming In functional programming, functions are the core building blocks In pure functional programming, functions are like mathematical functions Mathematical functions

More information

Ruby: Introduction, Basics

Ruby: Introduction, Basics Ruby: Introduction, Basics Computer Science and Engineering College of Engineering The Ohio State University Lecture 3 Ruby vs Java: Similarities Imperative and object-oriented Classes and instances (ie

More information

SUMMARY INTRODUCTION CONCURRENT PROGRAMMING THREAD S BASICS. Introduction Thread basics. Thread states. Sequence diagrams

SUMMARY INTRODUCTION CONCURRENT PROGRAMMING THREAD S BASICS. Introduction Thread basics. Thread states. Sequence diagrams SUMMARY CONCURRENT PROGRAMMING THREAD S BASICS PROGRAMMAZIONE CONCORRENTE E DISTR. Introduction Thread basics Thread properties Thread states Thread interruption Sequence diagrams Università degli Studi

More information

Some Scala problems for self

Some Scala problems for self Some Scala problems for self study@cs.lth.se May 4, 2012 2 Chapter 1 Getting Started 1.1 Background The book, Programming in Scala, Second Edition (PINS), is very good, and the best way to learn Scala

More information

Functions and Objects. Week 7: Symbolic Computation

Functions and Objects. Week 7: Symbolic Computation Week 7: Symbolic Computation In the previous weeks, we've seen the essential elements of modern functional programming: Functions (rst class) Types (parametric) Pattern Matching Lists This week, we'll

More information

Classes Classes 2 / 36

Classes Classes 2 / 36 Classes 1 / 36 Classes Classes 2 / 36 Anatomy of a Class By the end of next lecture, you ll understand everything in this class definition. package edu. gatech. cs1331. card ; import java. util. Arrays

More information

G Programming Languages - Fall 2012

G Programming Languages - Fall 2012 G22.2110-003 Programming Languages - Fall 2012 Lecture 4 Thomas Wies New York University Review Last week Control Structures Selection Loops Adding Invariants Outline Subprograms Calling Sequences Parameter

More information

Programming Language Pragmatics

Programming Language Pragmatics Chapter 10 :: Functional Languages Programming Language Pragmatics Michael L. Scott Historical Origins The imperative and functional models grew out of work undertaken Alan Turing, Alonzo Church, Stephen

More information

GETTING STARTED WITH Kotlin INTRODUCTION WHERE TO START CODING BASIC SYNTAX

GETTING STARTED WITH Kotlin INTRODUCTION WHERE TO START CODING BASIC SYNTAX 257 CONTENTS INTRODUCTION GETTING STARTED WITH Kotlin WHERE TO START CODING BASIC SYNTAX CONTROL FLOW: CONDITIONS CONTROL FLOW: LOOPS BASIC TYPES CLASSES FUNCTION TYPES AND LAMBDAS HIGHER-ORDER FUNCTIONS

More information

Lecture #23: Conversion and Type Inference

Lecture #23: Conversion and Type Inference Lecture #23: Conversion and Type Inference Administrivia. Due date for Project #2 moved to midnight tonight. Midterm mean 20, median 21 (my expectation: 17.5). Last modified: Fri Oct 20 10:46:40 2006 CS164:

More information

Functional Programming. Big Picture. Design of Programming Languages

Functional Programming. Big Picture. Design of Programming Languages Functional Programming Big Picture What we ve learned so far: Imperative Programming Languages Variables, binding, scoping, reference environment, etc What s next: Functional Programming Languages Semantics

More information