Practically Functional. Daniel Spiewak

Size: px
Start display at page:

Download "Practically Functional. Daniel Spiewak"

Transcription

1 Practically Functional Daniel Spiewak

2 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 and text parsing (ScalaBison, GLL Combinators, ScalaQL)

3 Agenda Define functional programming (sort of) See some common elements of FP Motivate why this stuff is useful in the real world (hopefully) Show practical functional techniques and design patterns Explain monads! Hopefully pique your interest in learning and applying more of this stuff

4 Definitions Q: What is functional programming?

5 Definitions Q: What is functional programming? A: Nobody knows!

6 Definitions Q: What is purely-functional?

7 Definitions Q: What is purely-functional? Everything is immutable (no variables)

8 Definitions Q: What is purely-functional? Everything is immutable (no variables) Absolutely no side-effects println("hello, World!")

9 Definitions Q: What is purely-functional? Everything is immutable (no variables) Absolutely no side-effects Referential transparency

10 Definitions Q: What is purely-functional? Everything is immutable (no variables) Absolutely no side-effects Referential transparency Bondage discipline?

11 Definitions Scala is not purely-functional vars Mutable collections Uncontrolled side-effects (println)

12 Definitions Scala is not purely-functional vars Mutable collections Uncontrolled side-effects (println) Is Scala a functional language?

13 Functional Trademarks Higher-order functions def foreach(f: String=>Unit) { f("what") f("is") f("going") f("on?")

14 Functional Trademarks Higher-order functions foreach { s => println(s)

15 Functional Trademarks Higher-order functions Closures are anonymous functions Ruby, Groovy, Python; none of these count! foreach(println)

16 Functional Trademarks Higher-order functions Closures are anonymous functions Ruby, Groovy, Python; none of these count! Singly-linked immutable lists (cons cells) val names = "Chris" :: "Joe" :: Nil val names2 = "Daniel" :: names

17 Functional Trademarks Higher-order functions Closures are anonymous functions Ruby, Groovy, Python; none of these count! Singly-linked immutable lists (cons cells) Usually some form of type-inference val me = "Daniel" // equivalent to... val me: String = "Daniel"

18 Functional Trademarks Higher-order functions Closures are anonymous functions Ruby, Groovy, Python; none of these count! Singly-linked immutable lists (cons cells) Usually some form of type-inference foreach { s => println(s)

19 Functional Trademarks Higher-order functions Closures are anonymous functions Ruby, Groovy, Python; none of these count! Singly-linked immutable lists (cons cells) Usually some form of type-inference Immutable by default (or encouraged) val me = "Daniel" var me = "Daniel"

20 What does this buy you? Modularity (separation of concerns) Understandability No more spooky action at a distance

21 What does this buy you? public class Company { private List<Person> employees; public List<Person> getemployees() { return employees; public void addemployee(person p) { if (p.isalive()) { employees.add(p);

22 What does this buy you? Modularity (separation of concerns) Understandability No more spooky action at a distance Flexible libraries (more on this later) Syntactic power (internal DSLs)

23 What does this buy you? "vector" should { "store a single element" in { val prop = forall { (i: Int, e: Int) => i >= 0 ==> { (vector(0) = e)(0) mustequal e prop must pass "implement length" in { val prop = forall { list: List[Int] => val vec = Vector(list:_*) vec.length mustequal list.length prop must pass

24 Functional Idioms Recursion instead of loops Scala helps with this by allowing methods within methods

25 Functional Idioms Recursion instead of loops Scala helps with this by allowing methods within methods def factorial(n: Int) = { var back = 1 for (i <- 1 to n) { back *= i back

26 Functional Idioms Recursion instead of loops Scala helps with this by allowing methods within methods def factorial(n: Int): Int = { if (n == 1) 1 else n * factorial(n - 1)

27 Functional Idioms Recursion instead of loops Scala helps with this by allowing methods within methods def factorial(n: Int) = { def loop(n: Int, acc: Int): Int = { if (n == 1) acc else loop(n - 1, acc * n) loop(n, 1)

28 Functional Idioms Recursion instead of loops Scala helps with this by allowing methods within methods Higher-order functions instead of recursion

29 Functional Idioms Recursion instead of loops Scala helps with this by allowing methods within methods Higher-order functions instead of recursion Combinators instead of higher-order functions

30 Functional Idioms Recursion instead of loops Scala helps with this by allowing methods within methods Higher-order functions instead of recursion Combinators instead of higher-order functions Monads!

31 Example #1 Retrieve structured, formatted data from across multiple.properties files and multiple keys within those files. # daniel.properties name.first = Daniel name.last = Spiewak age = 21 # tim.properties name.first = Timothy name.last = Olmsted age = 22

32 Example #1 Using loops

33 def toint(s: String) = try { s.toint catch { case _ => null // uninteresting and ugly def readfile(file: String): Map[String, String] = { import collection.jcl.hashtable try { val is = new BufferedInputStream(new FileInputStream(file)) val p = new Properties p.load(is) is.close() new Hashtable(p).asInstanceOf[Hashtable[String, String]] catch { case _ => null

34 import collection.mutable.listbuffer def readpeople(files: List[String]): List[Person] = { val back = new ListBuffer[Person] for (file <- files) { val props = readfile(file) if (props!= null) { if (props.contains("name.first") && props.contains("name.last") && props.contains("age")) { val age = toint(props("age")) if (age!= null) back += new Person(props("name.first"), props("name.last"), age) back.tolist

35 Example #1 Using loops Recursive

36 def readpeople(files: List[String]): List[Person] = files match { case file :: tail => { val props = readfile(file) val back = if (props!= null) { if (props.contains("name.first") && props.contains("name.last") && props.contains("age")) { val age = toint(props("age")) if (age!= null) new Person(props("name.first"), props("name.last"), age) else null else null else null if (back!= null) back :: readpeople(tail) else readpeople(tail) case Nil => Nil

37 Example #1 Loops Recursion Higher-order functions

38 def readpeople(files: List[String]): List[Person] = { files.foldright(list[string]()) { (file, people) => val props = readfile(file) val back = if (props!= null) { if (props.contains("name.first") && props.contains("name.last") && props.contains("age")) { val age = toint(props("age")) if (age!= null) new Person(props("name.first"), props("name.last"), age) else null else null else null if (back!= null) back :: people else people

39 Example #1 Loops Recursion Higher-order functions Monads!

40 def toint(s: String) = try { Some(s.toInt) catch { case _ => None // uninteresting and ugly def readfile(file: String): Option[Map[String, String]] = { import collection.jcl.hashtable try { val is = new BufferedInputStream(new FileInputStream(file)) val p = new Properties p.load(is) is.close() Some(new Hashtable(p).asInstanceOf[Hashtable[String, String]]) catch { case _ => None

41 def readpeople(files: List[String]): List[Person] = { for { file <- files props <- readfile(file) firstname <- props get "name.first" lastname <- props get "name.last" agestring <- props get "age" age <- toint(agestring) yield new Person(firstName, lastname, age)

42 Example #1 Loops Recursion Higher-order functions Combinators Monads!

43 def readpeople(files: List[String]) = { import Function._ files flatmap readfile flatmap { props => val fnames = props get "name.first" val names = fnames flatmap { (_, props get "name.last") val data = names flatmap { case (fn, ln) => (fn, ln, props get "age" map toint) data map tupled(new Person _)

44 What did we just see? foldleft / foldright Catamorphisms Use when you want to reduce all of the elements of a collection into a single result Capable of almost anything!

45 What did we just see? foldleft / foldright def sum(nums: List[Int]) = { nums.foldleft(0) { (x, y) => x + y

46 What did we just see? foldleft / foldright def sum(nums: List[Int]) = { nums.foldleft(0) { _ + _

47 What did we just see? foldleft / foldright def sum(nums: List[Int]) = { (0 /: nums) { _ + _

48 What did we just see? foldleft / foldright map Use when you want to transform every element of a collection, leaving the results in the corresponding location within a new collection

49 What did we just see? foldleft / foldright map val nums = List("1", "2", "3", "4", "5") nums map { str => str.toint

50 What did we just see? foldleft / foldright map val nums = List("1", "2", "3", "4", "5") nums map { _.toint

51 What did we just see? foldleft / foldright map flatmap (has two meanings) Collections: Use when you want to transform every element optionally Monads: Should have really been called bind (or >>=). More later

52 What did we just see? foldleft / foldright map flatmap (has two meanings) def tochararray(arr: Array[String]) = { arr flatmap { _.tochararray tochararray(array("daniel", "Spiewak")) // => Array('D', 'a', 'n', 'i', 'e', 'l', 'S', 'p', 'i', 'e', 'w', 'a', 'k')

53 Other Common Util Methods filter (used in for-comprehensions) val nums = List(1, 2, 3, 4, 5) nums filter { _ % 2 == 0

54 Other Common Util Methods filter (used in for-comprehensions) val nums = List(1, 2, 3, 4, 5) nums filter (0 == 2 %)

55 Other Common Util Methods filter (used in for-comprehensions) zip / zipwithindex zipwith (not available pre-2.8.0) val evens = List(2, 4, 6) val odds = List(1, 3, 5) evens zip odds // => List((1, 2), (3, 4), (5, 6))

56 Other Common Util Methods filter (used in for-comprehensions) zip / zipwithindex zipwith (not available pre-2.8.0) forall and exists val nums = List(1, 2, 3, 4, 5) nums forall { _ % 2 == 0 // => false

57 Other Common Util Methods filter (used in for-comprehensions) zip / zipwithindex zipwith (not available pre-2.8.0) forall and exists val nums = List(1, 2, 3, 4, 5) nums exists { _ % 2 == 0 // => true

58 Other Common Util Methods filter (used in for-comprehensions) zip / zipwithindex zipwith (not available pre-2.8.0) forall and exists take and drop val nums = List(5, 4, 3, 2, 1) nums take 2 // => List(5, 4)

59 Other Common Util Methods filter (used in for-comprehensions) zip / zipwithindex zipwith (not available pre-2.8.0) forall and exists take and drop val nums = List(5, 4, 3, 2, 1) nums drop 2 // => List(3, 2, 1)

60 Other Common Util Methods filter (used in for-comprehensions) zip / zipwithindex zipwith (not available pre-2.8.0) forall and exists take and drop foreach val names = List("Daniel", "Chris") names foreach println

61 Example #2 Comparing the prefix of a List[Char] to a given string. List[Char] String Result List('d', 'a', 'n', 'i', 'e', 'l') "dan" true List('d', 'a', 'n', 'i', 'e', 'l') "iel" false List('t', 'e', 's', 't') "testing" false List('t', 'e', 's', 't') "test" true

62 def isprefix(chars: List[Char], str: String) = { if (chars.lengthcompare(str.length) < 0) { false else { val trunc = chars take str.length trunc.zipwithindex forall { case (c, i) => c == str(i)

63 More About Combinators The Essence of Functional Programming Combine simple things to solve complex problems Very high level Think about Lego bricks

64 More About Combinators The best example: Parser Combinators def expr: Parser[Int] = ( num ~ "+" ~ expr ^^ { case (x, _, y) => x + y num ~ "-" ~ expr ^^ { case (x, _, y) => x - y num ) def num = """\d+""".r ^^ { _.toint

65 More About Combinators The best example: Parser Combinators def expr: Parser[Int] = ( num ~ "+" ~ expr ^^ { case (x, _, y) => x + y num ~ "-" ~ expr ^^ { case (x, _, y) => x - y num ) def num = """\d+""".r ^^ { _.toint expr(" ") expr("42") // => Success(15) // => Success(42)

66 More About Combinators Three Types of Combinators Sequential (first a, then b) a ~ b

67 More About Combinators Three Types of Combinators Sequential (first a, then b) Disjunctive (either a, or b) a b

68 More About Combinators Three Types of Combinators Sequential (first a, then b) Disjunctive (either a, or b) Literal (exactly foo) "foo"

69 More About Combinators Three Types of Combinators Sequential (first a, then b) Disjunctive (either a, or b) Literal (exactly foo) Note: Our example uses a regular expression parser, but that is only a generalization of the literal parser

70 More About Combinators Seldom created, often used Good for problems which split into smaller sub-problems

71 March of the Monads Monads are not scary

72 March of the Monads Monads are not scary Monad explanations are scary

73 March of the Monads Monads are little containers for encapsulating something What the something is depends on the monad An instance of a monad can be bound together with another instance of that monad Most combinators are monads

74 March of the Monads All monads have A type constructor class Option[A] { A single-argument constructor new Some("one to watch over me") A flatmap method which behaves properly a flatmap { v => v.next

75 March of the Monads

76 March of the Monads Option This is what the Groovy folks really wanted when they designed the Elvis Operator Parser Sequential parser is really two bound parsers Disjunctive parser uses an optional monadic function: orelse Literal parser is the one-argument constructor Function1 (sort of) We could say that function composition is like a bind operation, but Scala didn t do that

77 Learn More Read my blog! :-) Some better sources A really good paper Monadic Parser Combinators (1996; Hutton, Meijer)

List are immutable Lists have recursive structure Lists are homogeneous

List are immutable Lists have recursive structure Lists are homogeneous WORKING WITH LISTS val fruit = List("apples", "oranges", "pears") val nums: List[Int] = List(1, 2, 3, 4) val diag3 = List( List(1, 0, 0), List(0, 1, 0), List(0, 0, 1) ) val empty = List() List are immutable

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

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

CompSci 220. Programming Methodology 12: Functional Data Structures

CompSci 220. Programming Methodology 12: Functional Data Structures CompSci 220 Programming Methodology 12: Functional Data Structures A Polymorphic Higher- Order Function def findfirst[a](as: Array[A], p: A => Boolean): Int = { def loop(n: Int): Int = if (n >= as.length)

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

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. 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

// Body of shortestlists starts here y flatmap { case Nil => Nil case x :: xs => findshortest(list(x), xs)

// Body of shortestlists starts here y flatmap { case Nil => Nil case x :: xs => findshortest(list(x), xs) 8 Shortest-strings Problem: Partial-Solution Dump Drew McDermott drew.mcdermott@yale.edu Lecture notes for 2016-09-19, revised 20016-09-25 Here is the state of play in solving the little puzzle about finding

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

Summer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define

Summer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define CS 6A Scheme Summer 207 Discussion 0: July 25, 207 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs,

More information

Strings are not collections, but they behave like them in almost every way. For example,

Strings are not collections, but they behave like them in almost every way. For example, Functional Programming Style Drew McDermott drew.mcdermott@yale.edu 2015-09-30 & 10-02 Revised 2015-10-15, by addition of paragraph on type ascription in case clauses at the end of the section Variable

More information

Haskell: From Basic to Advanced. Part 2 Type Classes, Laziness, IO, Modules

Haskell: From Basic to Advanced. Part 2 Type Classes, Laziness, IO, Modules Haskell: From Basic to Advanced Part 2 Type Classes, Laziness, IO, Modules Qualified types In the types schemes we have seen, the type variables were universally quantified, e.g. ++ :: [a] -> [a] -> [a]

More information

SCHEME 8. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. March 23, 2017

SCHEME 8. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. March 23, 2017 SCHEME 8 COMPUTER SCIENCE 61A March 2, 2017 1 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs,

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

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

INTRODUCTION. SHORT INTRODUCTION TO SCALA INGEGNERIA DEL SOFTWARE Università degli Studi di Padova SHORT INTRODUCTION TO SCALA INGEGNERIA DEL SOFTWARE Università degli Studi di Padova Dipartimento di Matematica Corso di Laurea in Informatica, A.A. 2014 2015 rcardin@math.unipd.it INTRODUCTION Object/functional

More information

Introduction to Typed Racket. The plan: Racket Crash Course Typed Racket and PL Racket Differences with the text Some PL Racket Examples

Introduction to Typed Racket. The plan: Racket Crash Course Typed Racket and PL Racket Differences with the text Some PL Racket Examples Introduction to Typed Racket The plan: Racket Crash Course Typed Racket and PL Racket Differences with the text Some PL Racket Examples Getting started Find a machine with DrRacket installed (e.g. the

More information

CSE341 Spring 2017, Final Examination June 8, 2017

CSE341 Spring 2017, Final Examination June 8, 2017 CSE341 Spring 2017, Final Examination June 8, 2017 Please do not turn the page until 8:30. Rules: The exam is closed-book, closed-note, etc. except for both sides of one 8.5x11in piece of paper. Please

More information

CSE341: Programming Languages Lecture 9 Function-Closure Idioms. Dan Grossman Winter 2013

CSE341: Programming Languages Lecture 9 Function-Closure Idioms. Dan Grossman Winter 2013 CSE341: Programming Languages Lecture 9 Function-Closure Idioms Dan Grossman Winter 2013 More idioms We know the rule for lexical scope and function closures Now what is it good for A partial but wide-ranging

More information

Don t Drive on the Railroad Tracks. Eugene Wallingford University of Northern Iowa November 17, 2010

Don t Drive on the Railroad Tracks. Eugene Wallingford University of Northern Iowa November 17, 2010 Don t Drive on the Railroad Tracks Eugene Wallingford University of Northern Iowa November 17, 2010 Two Claims In the small, you know this. It is no big deal. In the large, this is different. It changes

More information

CSE 413 Languages & Implementation. Hal Perkins Winter 2019 Structs, Implementing Languages (credits: Dan Grossman, CSE 341)

CSE 413 Languages & Implementation. Hal Perkins Winter 2019 Structs, Implementing Languages (credits: Dan Grossman, CSE 341) CSE 413 Languages & Implementation Hal Perkins Winter 2019 Structs, Implementing Languages (credits: Dan Grossman, CSE 341) 1 Goals Representing programs as data Racket structs as a better way to represent

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

Introduction to Haskell

Introduction to Haskell Introduction to Haskell Matt Mullins Texas A&M Computing Society October 6, 2009 Matt Mullins (TACS) Introduction to Haskell October 6, 2009 1 / 39 Outline Introduction to Haskell Functional Programming

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

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

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

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

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

CSE341 Spring 2017, Final Examination June 8, 2017

CSE341 Spring 2017, Final Examination June 8, 2017 CSE341 Spring 2017, Final Examination June 8, 2017 Please do not turn the page until 8:30. Rules: The exam is closed-book, closed-note, etc. except for both sides of one 8.5x11in piece of paper. Please

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

TAIL RECURSION, SCOPE, AND PROJECT 4 11

TAIL RECURSION, SCOPE, AND PROJECT 4 11 TAIL RECURSION, SCOPE, AND PROJECT 4 11 COMPUTER SCIENCE 61A Noveber 12, 2012 1 Tail Recursion Today we will look at Tail Recursion and Tail Call Optimizations in Scheme, and how they relate to iteration

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

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

Computer Science 21b (Spring Term, 2015) Structure and Interpretation of Computer Programs. Lexical addressing

Computer Science 21b (Spring Term, 2015) Structure and Interpretation of Computer Programs. Lexical addressing Computer Science 21b (Spring Term, 2015) Structure and Interpretation of Computer Programs Lexical addressing The difference between a interpreter and a compiler is really two points on a spectrum of possible

More information

INF 212 ANALYSIS OF PROG. LANGS FUNCTION COMPOSITION. Instructors: Crista Lopes Copyright Instructors.

INF 212 ANALYSIS OF PROG. LANGS FUNCTION COMPOSITION. Instructors: Crista Lopes Copyright Instructors. INF 212 ANALYSIS OF PROG. LANGS FUNCTION COMPOSITION Instructors: Crista Lopes Copyright Instructors. Topics Recursion Higher-order functions Continuation-Passing Style Monads (take 1) Identity Monad Maybe

More information

CSE341: Programming Languages Lecture 9 Function-Closure Idioms. Dan Grossman Fall 2011

CSE341: Programming Languages Lecture 9 Function-Closure Idioms. Dan Grossman Fall 2011 CSE341: Programming Languages Lecture 9 Function-Closure Idioms Dan Grossman Fall 2011 More idioms We know the rule for lexical scope and function closures Now what is it good for A partial but wide-ranging

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

INF 102 CONCEPTS OF PROG. LANGS FUNCTIONAL COMPOSITION. Instructors: James Jones Copyright Instructors.

INF 102 CONCEPTS OF PROG. LANGS FUNCTIONAL COMPOSITION. Instructors: James Jones Copyright Instructors. INF 102 CONCEPTS OF PROG. LANGS FUNCTIONAL COMPOSITION Instructors: James Jones Copyright Instructors. Topics Recursion Higher-order functions Continuation-Passing Style Monads (take 1) Identity Monad

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

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

Linked lists and the List class

Linked lists and the List class Linked lists and the List class Cheong 1 Linked lists So far, the only container object we used was the array. An array is a single object that contains references to other objects, possibly many of them.

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

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

CSE413: Programming Languages and Implementation Racket structs Implementing languages with interpreters Implementing closures

CSE413: Programming Languages and Implementation Racket structs Implementing languages with interpreters Implementing closures CSE413: Programming Languages and Implementation Racket structs Implementing languages with interpreters Implementing closures Dan Grossman Fall 2014 Hi! I m not Hal J I love this stuff and have taught

More information

Scheme as implemented by Racket

Scheme as implemented by Racket Scheme as implemented by Racket (Simple view:) Racket is a version of Scheme. (Full view:) Racket is a platform for implementing and using many languages, and Scheme is one of those that come out of the

More information

Life in a Post-Functional World

Life in a Post-Functional World Life in a Post-Functional World Definitions Functional Programming Definitions Functional Programming Programming with functions! Definitions Functional Programming Programming with functions! Functions

More information

JSJS - Project Proposal

JSJS - Project Proposal JSJS - Project Proposal A general purpose, strongly typed programming language for the web Jain Bahul Srivastav Prakhar Jain Ayush Sadekar Gaurang bkj2111 ps2894 aj2672 gss2147 Description JSJS is a strongly

More information

Functions & First Class Function Values

Functions & First Class Function Values Functions & First Class Function Values PLAI 1st ed Chapter 4, PLAI 2ed Chapter 5 The concept of a function is itself very close to substitution, and to our with form. Consider the following morph 1 {

More information

Scala Style Guide Spring 2018

Scala Style Guide Spring 2018 CS18 Integrated Introduction to Computer Science Fisler, Nelson Scala Style Guide Spring 2018 Contents 1 Introduction 1 2 Naming 1 3 Formatting 2 4 Class Declarations 3 5 Functional Paradigms 4 6 Comments

More information

CS 360 Programming Languages Interpreters

CS 360 Programming Languages Interpreters CS 360 Programming Languages Interpreters Implementing PLs Most of the course is learning fundamental concepts for using and understanding PLs. Syntax vs. semantics vs. idioms. Powerful constructs like

More information

Introduction to Functional Programming and Haskell. Aden Seaman

Introduction to Functional Programming and Haskell. Aden Seaman Introduction to Functional Programming and Haskell Aden Seaman Functional Programming Functional Programming First Class Functions Expressions (No Assignment) (Ideally) No Side Effects Different Approach

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

COMP 181. Agenda. Midterm topics. Today: type checking. Purpose of types. Type errors. Type checking

COMP 181. Agenda. Midterm topics. Today: type checking. Purpose of types. Type errors. Type checking Agenda COMP 181 Type checking October 21, 2009 Next week OOPSLA: Object-oriented Programming Systems Languages and Applications One of the top PL conferences Monday (Oct 26 th ) In-class midterm Review

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

G Programming Languages - Fall 2012

G Programming Languages - Fall 2012 G22.2110-003 Programming Languages - Fall 2012 Lecture 3 Thomas Wies New York University Review Last week Names and Bindings Lifetimes and Allocation Garbage Collection Scope Outline Control Flow Sequencing

More information

Web Application Development

Web Application Development Web Application Development Produced by David Drohan (ddrohan@wit.ie) Department of Computing & Mathematics Waterford Institute of Technology http://www.wit.ie JavaScript JAVASCRIPT FUNDAMENTALS Agenda

More information

SCALAMODULES A Scala DSL to ease OSGi development Heiko Seeberger, WeigleWilczek

SCALAMODULES A Scala DSL to ease OSGi development Heiko Seeberger, WeigleWilczek SCALAMODULES A Scala DSL to ease OSGi development Heiko Seeberger, WeigleWilczek WHAT S SCALA? mature object-functional statically typed lightweight WHAT S SCALA? expressive concise pragmatic interoperabel

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

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

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

Spring 2018 Discussion 7: March 21, Introduction. 2 Primitives

Spring 2018 Discussion 7: March 21, Introduction. 2 Primitives CS 61A Scheme Spring 2018 Discussion 7: March 21, 2018 1 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme

More information

Parametricity. Types Are Documentation. Tony Morris

Parametricity. Types Are Documentation. Tony Morris Parametricity Types Are Documentation Tony Morris The Journey Fast and loose reasoning is morally correct Danielsson, Hughes, Jansson & Gibbons [DHJG06] tell us: Functional programmers often reason about

More information

CSE 130, Fall 2006: Final Examination

CSE 130, Fall 2006: Final Examination CSE 130, Fall 2006: Final Examination Name: ID: Instructions, etc. 1. Write your answers in the space provided. 2. Wherever it says explain, write no more than three lines as explanation. The rest will

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

Principles of Programming Languages

Principles of Programming Languages Principles of Programming Languages www.cs.bgu.ac.il/~ppl172 Lesson 6 - Defining a Programming Language Bottom Up Collaboration and Management - Elements of Programming Dana Fisman 1 What we accomplished

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

CS 320: Concepts of Programming Languages

CS 320: Concepts of Programming Languages CS 320: Concepts of Programming Languages Wayne Snyder Computer Science Department Boston University Lecture 03: Bare-Bones Haskell Continued: o Function Application = Rewriting by Pattern Matching o Haskell

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

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

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

CSE341 Autumn 2017, Final Examination December 12, 2017

CSE341 Autumn 2017, Final Examination December 12, 2017 CSE341 Autumn 2017, Final Examination December 12, 2017 Please do not turn the page until 2:30. Rules: The exam is closed-book, closed-note, etc. except for both sides of one 8.5x11in piece of paper. Please

More information

INTRODUCTION TO SCHEME

INTRODUCTION TO SCHEME INTRODUCTION TO SCHEME PRINCIPLES OF PROGRAMMING LANGUAGES Norbert Zeh Winter 2019 Dalhousie University 1/110 SCHEME: A FUNCTIONAL PROGRAMMING LANGUAGE Functions are first-class values: Can be passed as

More information

Under the Hood of Scala Implicits. by Alexander Podkhalyuzin ScalaDays San Francisco 2015

Under the Hood of Scala Implicits. by Alexander Podkhalyuzin ScalaDays San Francisco 2015 Under the Hood of Scala Implicits by Alexander Podkhalyuzin ScalaDays San Francisco 2015 Agenda How implicits work How IDE can help with them Possibilities to improve performance of compilation and IDE

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

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

CSE 341, Autumn 2005, Assignment 3 ML - MiniML Interpreter

CSE 341, Autumn 2005, Assignment 3 ML - MiniML Interpreter Due: Thurs October 27, 10:00pm CSE 341, Autumn 2005, Assignment 3 ML - MiniML Interpreter Note: This is a much longer assignment than anything we ve seen up until now. You are given two weeks to complete

More information

CMSC 330: Organization of Programming Languages. OCaml Imperative Programming

CMSC 330: Organization of Programming Languages. OCaml Imperative Programming CMSC 330: Organization of Programming Languages OCaml Imperative Programming CMSC330 Fall 2017 1 So Far, Only Functional Programming We haven t given you any way so far to change something in memory All

More information

Who am I? Harlan Iverson. Programming enthusiast. Seeker of truth. Imperfect. I'll be wrong about some things. Please correct me if you can.

Who am I? Harlan Iverson. Programming enthusiast. Seeker of truth. Imperfect. I'll be wrong about some things. Please correct me if you can. Who am I? Harlan Iverson. Programming enthusiast. Seeker of truth. Imperfect. I'll be wrong about some things. Please correct me if you can. P.S... I hate boring presentations. Please, engage and stay

More information

Functional Programming

Functional Programming Functional Programming Final Exam Friday, December 18 2015 First Name: Last Name: Your points are precious, don t let them go to waste! Your Name Work that can t be attributed to you is lost: write your

More information

A First Look at ML. Chapter Five Modern Programming Languages, 2nd ed. 1

A First Look at ML. Chapter Five Modern Programming Languages, 2nd ed. 1 A First Look at ML Chapter Five Modern Programming Languages, 2nd ed. 1 ML Meta Language One of the more popular functional languages (which, admittedly, isn t saying much) Edinburgh, 1974, Robin Milner

More information

CSCC24 Functional Programming Typing, Scope, Exceptions ML

CSCC24 Functional Programming Typing, Scope, Exceptions ML CSCC24 Functional Programming Typing, Scope, Exceptions ML Carolyn MacLeod 1 winter 2012 1 Based on slides by Anya Tafliovich, with many thanks to Gerald Penn and Sheila McIlraith. motivation Consider

More information

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

CSE341 Section 3. Standard-Library Docs, First-Class Functions, & More

CSE341 Section 3. Standard-Library Docs, First-Class Functions, & More CSE341 Section 3 Standard-Library Docs, First-Class Functions, & More Adapted from slides by Daniel Snitkovskiy, Nick Mooney, Nicholas Shahan, Patrick Larson, and Dan Grossman Agenda 1. SML Docs Standard

More information

CS558 Programming Languages

CS558 Programming Languages CS558 Programming Languages Winter 2018 Lecture 7b Andrew Tolmach Portland State University 1994-2018 Dynamic Type Checking Static type checking offers the great advantage of catching errors early And

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

SCHEME AND CALCULATOR 5b

SCHEME AND CALCULATOR 5b SCHEME AND CALCULATOR 5b COMPUTER SCIENCE 6A July 25, 203 In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs,

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

CSci 4223 Lecture 12 March 4, 2013 Topics: Lexical scope, dynamic scope, closures

CSci 4223 Lecture 12 March 4, 2013 Topics: Lexical scope, dynamic scope, closures CSci 4223 Lecture 12 March 4, 2013 Topics: Lexical scope, dynamic scope, closures 1 Lexical Scope SML, and nearly all modern languages, follow the Rule of Lexical Scope: the body of a function is evaluated

More information

Conversions and Overloading : Overloading

Conversions and Overloading : Overloading Conversions and Overloading : First. Java allows certain implicit conversations of a value of one type to a value of another type. Implicit conversations involve only the primitive types. For example,

More information

Outline. Collections Arrays vs. Lists Functions using Arrays/Lists Higher order functions using Arrays/Lists

Outline. Collections Arrays vs. Lists Functions using Arrays/Lists Higher order functions using Arrays/Lists Arrays and Lists Outline Collections Arrays vs. Lists Functions using Arrays/Lists Higher order functions using Arrays/Lists Collections We've seen tuples to store multiple objects together, but the tuple

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

CS457/557 Functional Languages

CS457/557 Functional Languages CS457/557 Functional Languages Spring 2018 Lecture 1: Course Introduction Andrew Tolmach Portland State University (with thanks to Mark P. Jones) 1 Goals of this course Introduce the beautiful ideas of

More information

Programming Languages

Programming Languages Programming Languages Andrea Flexeder Chair for Theoretical Computer Science Prof. Seidl TU München winter term 2010/2011 Lecture 10 Side-Effects Main Points you should get: Why monads? What is a monad?

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

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

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

Dialects of ML. CMSC 330: Organization of Programming Languages. Dialects of ML (cont.) Features of ML. Functional Languages. Features of ML (cont.

Dialects of ML. CMSC 330: Organization of Programming Languages. Dialects of ML (cont.) Features of ML. Functional Languages. Features of ML (cont. CMSC 330: Organization of Programming Languages OCaml 1 Functional Programming Dialects of ML ML (Meta Language) Univ. of Edinburgh,1973 Part of a theorem proving system LCF The Logic of Computable Functions

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

OCaml Data CMSC 330: Organization of Programming Languages. User Defined Types. Variation: Shapes in Java

OCaml Data CMSC 330: Organization of Programming Languages. User Defined Types. Variation: Shapes in Java OCaml Data : Organization of Programming Languages OCaml 4 Data Types & Modules So far, we ve seen the following kinds of data Basic types (int, float, char, string) Lists Ø One kind of data structure

More information

Functional Programming

Functional Programming The Meta Language (ML) and Functional Programming Daniel S. Fava danielsf@ifi.uio.no Department of informatics University of Oslo, Norway Motivation ML Demo Which programming languages are functional?

More information

Monadologie. professional help for type anxiety. Christopher League 12 July 2010

Monadologie. professional help for type anxiety. Christopher League 12 July 2010 Monadologie professional help for type anxiety Christopher League 12 July 2010 Monadologie github.com/league/scala-type-anxiety @chrisleague league@contrapunctus.net 1996 Principles of Programming Languages

More information