# An introduction introduction to functional functional programming programming using usin Haskell

Size: px
Start display at page:

## Transcription

1 An introduction to functional programming using Haskell Anders Møller

2 Haskell The most popular p purely functional, lazy programming g language Functional programming language : a program is a collection of mathematical functions Purely functional : all variables refer to immutable, persistent values that is, new values can be created, but existing ones cannot be modified! Lazy : expressions ess s are evaluated ed by need 2

3 Example: QuickSort in Java void qsort(int[] a, int lo, int hi) { if (lo < hi) { int l = lo; int h = hi; int p = a[lo]; do { while (l < h && a[l] <= p) l = l+1; while (h > l && a[h] >= p) h = h-1; if (l < h) { int t = a[l]; a[l] = a[h]; a[h] = t; } } while (l < h); int t = a[h]; a[h] = a[lo]; a[lo] = t; qsort(a, lo, h-1); gq qsort(a, h+1, hi); } } Mini-exercise: Sort the list [4,8,1,7] using QuickSort 3

4 Example: QuickSort in Haskell qsort [] = [] qsort (x:xs) = qsort lt ++ [x] ++ qsort greq where lt = [y y <- xs, y < x] greq = [y y <- xs, y >= x] The program is the specification! List operations: [] the empty list x:xs adds an element x to the head of a list xs xs ++ ys concatenates two lists xs and ys [x,y,z] abbreviation of x:(y:(z:[])) 4

5 Overview Definitions, functions, expressions, and values Strong typing Recursive data structures Higher-order functions Programming styles, performance Reasoning about program behavior 5

6 Definitions, functions, expressions, and values len [] = 0 len (x:xs) = len xs + 1 numbers = [7,9,13] n = len numbers Function application can be written without parentheses Functions are reminiscent of methods in Java, but 6

7 Evaluation through pattern matching and expression rewriting i len [] = 0 len (x:xs) = len xs + 1 numbers = [7,9,13] n = len numbers n len numbers len [7,9,13] len 7:[9,13] len [9,13] + 1 len 9:[13] + 1 len [13] len 13:[] len [] Actual evaluation may proceed in a different order, but the resulting value is the same 7

8 let expressions len [] = 0 len (x:xs) = len xs + 1 numbers = [7,9,13] n = len numbers numbers = [7,9,13] n = let len [] = 0 len (x:xs) = len xs + 1 in len numbers 8

9 where clauses len [] = 0 len (x:xs) = len xs + 1 numbers = [7,9,13] n = len numbers numbers = [7,9,13] n = let len [] = 0 len (x:xs) = len xs + 1 in len numbers numbers = [7,9,13], n = len numbers where len [] = 0 len (x:xs) = len xs + 1 9

10 case expressions len [] = 0 len (x:xs) = len xs + 1 numbers = [7,9,13] n = len numbers numbers = [7,9,13] n = let len [] = 0 len ys = case len ys (x:xs) of = len xs + 1 in [] len -> numbers 0 numbers = [7,9,13] x:xs -> len xs + 1 n = len numbers where numbers len = [][7,9,13] = 0 n = len (x:xs) numbers = len xs

11 Wildcard pattern len [] = 0 len (x:xs) = len xs + 1 numbers = [7,9,13] n = len numbers len (x:xs) = len xs + 1 numbers len _ = = [7,9,13] 0 n = let len [] = 0 len ys = numbers case len ys (x:xs) = of [7,9,13] = len xs + 1 in n = [] len -> numbers 0 numbers = [7,9,13] x:xs -> len xs + 1 n = len numbers where numbers len = [][7,9,13] = 0 n = len (x:xs) numbers = len xs

12 Pattern matching, if-then-else, else, and guards Multiple function definitions with the same function name case expressions if-then-else expressions: if e 1 then e 2 else e case e 1 of 3 True -> e 2 Guards: False -> e 3 sign x x > 0 = 1 x == 0 = 0 x < 0 = -1 12

13 Iteration and recursion We don t need loops when we have recursion Divide and conquer! len [] = 0 len (x:xs) = len xs + 1 qsort [] = [] qsort (x:xs) = qsort lt ++ [x] ++ qsort greq where lt = [y y <- xs, y < x] greq = [y y <- xs, y >= x] 13

14 Layout of Haskell programs numbers = [7,9,13] n = let len [] = 0 len (x:xs) = len xs + 1 in len numbers len (x:xs) = len xs + 1 in len numbers numbers = [7,9,13] n = let len [] = 0 numbers = [7,9,13] n = let {len [] = 0; len (x:xs) = len xs + 1} in len numbers 14

15 Comments -- computes the length of a list len [] = 0 len (x:xs) = len xs + 1 {- numbers = [7,9,13] n = len numbers -} 15

16 Quiz! Write a function rev that reverses a given list for example, rev [7,9,13] [13,9,7] (don t worry about performance for now...) Hint: recall the definition of len: len [] = 0 len (x:xs) = len xs

17 Overview Definitions, functions, expressions, and values Strong typing Recursive data structures Higher-order functions Programming styles, performance Reasoning about program behavior 17

18 Strong typing len :: [Integer] -> Integer len [] = 0 len (x:xs) = len xs + 1 numbers :: [Integer] numbers = [7,9,13] n :: Integer n = len numbers Every expression has a type The Haskell static type checker makes sure you are not mixing i apples and bananas 18

19 Types Integer, String, Float, Char,... base types [X] a list of X values X -> Y a function from X values to Y values (X,Y,Z) a tuple of an X value, a Y value, and a Z value... pair_sum :: (Integer,Integer) -> Integer pair_sum (a,b) = a + b x :: (Integer,(String,Integer),Char) x = (7,( Foo,42), a ) 19

20 Type errors at compile-time qsort [] = [] qsort (x:xs) = qsort lt + [x] + qsort greq where lt = [y y <- xs, y < x] Can you spot the error? The Hugs tool: greq = [y y <- xs, y >= x] ERROR: example.hs :42 Cannot infer instance *** Instance : Num [a] *** Expression : qsort The error is found, but the quality of type error messages is not always great... 20

21 Type inference A type annotation is a contract between the author and the user of a function definition In Haskell, writing type annotations is optional use them to express the intended meaning of your functions omit them if the meaning is obvious (Compare this with Java!) When omitted, Haskell finds the type for you!...in fact, the best possible type! (also called, the principal type) More about type inference later... 21

22 Overview Definitions, functions, expressions, and values Strong typing Recursive data structures Higher-order functions Programming styles, performance Reasoning about program behavior 22

23 Type definitions data Color = Red Green Blue f Red = 1 f Green = 2 f Blue data = Shape 3 = Rectangle Float Float Circle Float area (Rectangle x y) = x * y area (Circle r) = pi * r * r Red, Green, Blue, Rectangle, and Circle are called constructors t 23

24 Constructors vs. pattern matching Constructors are special functions that construct values example: Rectangle constructs a Shape value Pattern matching can be used to destruct values example: getx (Rectangle x y) = x defines a function that can extract the x component of a Rectangle value 24

25 Recursive data structures Type definitions can be recursive! data Expr = Const Float Add Expr Expr Neg Expr Mult Expr Expr eval (Const c) = c Mult Const Add 2.0 eval (Add e1 e2) = eval e1 + eval e2 eval (Neg e) = - eval e eval (Mult e1 e2) = eval e1 * eval e2 Const Const eval (Mult (Const 2.0) (Add (Const 3.0) (Const 4.0)))

26 Type synonyms type String = [Char] type Name = String data OptionalAddress = None Addr String type Person = (Name,OptionalAddress) Type synonyms are just abbreviations... 26

27 Naming requirements The naming style we have been using is mandatory: Type names and constructor names begin with an upper-case letter (e.g. Expr or Rectangle) Value names begin with a lower-case letter (e.g. qsort or x) ) 27

28 Quiz! Given the type definition data TreeNode = Leaf Integer Branch TreeNode TreeNode write a function leafsum that computes the sum of the leaf values for a given TreeNode structure 28

29 Overview Definitions, functions, expressions, and values Strong typing Recursive data structures Higher-order functions Programming styles, performance Reasoning about program behavior 29

30 Higher-order functions Functions are first-class values! (unlike methods in Java...) Functions can take functions as arguments and return functions map f [] = [] map f (x:xs) = f x : map f xs numbers = [7,9,13] inc x = x + 1 more_numbers = map inc numbers Function application associates to the left: f x y (f x) y 30

31 Currying add_a :: (Integer,Integer) Integer) -> Integer add_a (x,y) = x + y add_b :: Integer -> Integer -> Integer add_b x y = x + y inc = add_b 1 add_a takes a pair of integers as argument and returns their sum add_b takes one integer as argument and returns a function that t takes another integer as argument and returns their sum This trick is named after Haskell B. Curry ( ) 31

32 Anonymous functions A λ-abstractionb t ti is an anonymous function Traditional syntax: λx.exp Haskell syntax: \x -> exp where x is a variable name and exp is an expression that may use x (λ is like a quantifier) inc x = x + 1 inc = \x -> x + 1 add x y = x + y add = \x -> \y -> x + y 32

33 Infix operators Infix operators (e.g. + or ++) are just binary functions! x + y (+) x y Binary functions can be written with an infix notation add x y x `add` y Operator precedence and associativity can be specified with fixity declarations... 33

34 Haskell standard prelude A library containing commonly used definitions Examples: [] ++ ys = ys (x:xs) ++ ys = x : (xs ++ ys) True && x = x False && _ = False type String = [Char] data Bool = False True The core of Haskell is quite small Theoretically, everything can be reduced to the λ-calculus... 34

35 List comprehensions Lists are pervasive in Haskell... lt = [y y <- xs, y < x] means the same as lt = concatmap f xs where f y y < x = [y] otherwise = [] (concatmap is defined in the standard prelude) 35

36 An operation on lists: zip zip takes two lists as input (Curry style) and returns a list of pairs Example: zip [1,2,3], ['a','b','c'], evaluates to [(1,'a'),(2,'b'),(3,'c')] How is zip defined? zip (x:xs) (y:ys) = (x,y) : zip xs ys zip [] ys = [] zip xs [] = [] 36

37 Quiz! Explain why the following 3 definitions have the same meaning and describe what they do: (f. g) x = f (g x) (.) f g x = f (g x) f. g = \x -> f (g x) 37

38 Overview Definitions, functions, expressions, and values Strong typing Recursive data structures Higher-order functions Programming styles, performance Reasoning about program behavior 38

39 Syntactic redundancy Expression style vs. Declaration style each function is defined d as one expression each function is defined d as a series of equations let where λ arguments on left-hand-side of = case function-level l pattern matching if guards 39

40 A note on performance Being in math world doesn t mean that we can ignore performance... Assume that we define reverse by reverse [] = [] reverse (x:xs) = reverse xs ++ [x] Recall that ++ is defined by [] ++ ys = ys (x:xs) ++ ys = x : (xs ++ ys) Computing reverse zs takes time O(n 2 ) where n is the length of zs 40

41 Afasterreverse reverse using an accumulator reverse zs = rev [] zs where rev acc [] = acc rev acc (x:xs) = rev (x:acc) xs reverse [7,9,13] rev [] [7,9,13] rev [7] [9,13] rev [9,7] [13] rev [13,9,7] [] [13,9,7] Computing reverse zs now takes time O(n ) where n is the length of zs Moral: you have to know how programs are evaluated 41

42 Overview Definitions, functions, expressions, and values Strong typing Recursive data structures Higher-order functions Programming styles, performance Reasoning about program behavior 42

43 Referential transparency Purely functional means that evaluation has no side-effects a function maps input to output and does nothing else, just like a real mathematical function Referential transparency: equals can be substituted for equals can disregard d order and duplication of evaluation ation 43

44 Referential transparency Easier for the programmer (and the compiler) to reason about program behavior Example: f(x)*f(x) always has the same behavior as let z=f(x) in z*z (which is not true for Java!) More about proving properties of programs later... 44

45 Summary Haskell is purely functional Recursive data structures Pattern matching Higher-order ode functions Strong typing advanced features in the next lecture 45

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

### Lecture 19: Functions, Types and Data Structures in Haskell

The University of North Carolina at Chapel Hill Spring 2002 Lecture 19: Functions, Types and Data Structures in Haskell Feb 25 1 Functions Functions are the most important kind of value in functional programming

### A general introduction to Functional Programming using Haskell

A general introduction to Functional Programming using Haskell Matteo Rossi Dipartimento di Elettronica e Informazione Politecnico di Milano rossi@elet.polimi.it 1 Functional programming in a nutshell

### Shell CSCE 314 TAMU. Haskell Functions

1 CSCE 314: Programming Languages Dr. Dylan Shell Haskell Functions 2 Outline Defining Functions List Comprehensions Recursion 3 Conditional Expressions As in most programming languages, functions can

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

### PROGRAMMING IN HASKELL. Chapter 2 - First Steps

PROGRAMMING IN HASKELL Chapter 2 - First Steps 0 The Hugs System Hugs is an implementation of Haskell 98, and is the most widely used Haskell system; The interactive nature of Hugs makes it well suited

### PROGRAMMING IN HASKELL. CS Chapter 6 - Recursive Functions

PROGRAMMING IN HASKELL CS-205 - Chapter 6 - Recursive Functions 0 Introduction As we have seen, many functions can naturally be defined in terms of other functions. factorial :: Int Int factorial n product

### CSCE 314 TAMU Fall CSCE 314: Programming Languages Dr. Flemming Andersen. Haskell Functions

1 CSCE 314: Programming Languages Dr. Flemming Andersen Haskell Functions 2 Outline Defining Functions List Comprehensions Recursion 3 Conditional Expressions As in most programming languages, functions

### Shell CSCE 314 TAMU. Functions continued

1 CSCE 314: Programming Languages Dr. Dylan Shell Functions continued 2 Outline Defining Functions List Comprehensions Recursion 3 A Function without Recursion Many functions can naturally be defined in

### 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]

### CS 360: Programming Languages Lecture 10: Introduction to Haskell

CS 360: Programming Languages Lecture 10: Introduction to Haskell Geoffrey Mainland Drexel University Thursday, February 5, 2015 Adapted from Brent Yorgey s course Introduction to Haskell. Section 1 Administrivia

### CSCE 314 TAMU Fall CSCE 314: Programming Languages Dr. Flemming Andersen. Haskell Basics

1 CSCE 314: Programming Languages Dr. Flemming Andersen Haskell Basics 2 Contents 1. Jump into Haskell: Using ghc and ghci (more detail) 2. Historical Background of Haskell 3. Lazy, Pure, and Functional

### Haskell Overview II (2A) Young Won Lim 8/9/16

(2A) Copyright (c) 2016 Young W. Lim. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later version published

### CSCE 314 Programming Languages

CSCE 314 Programming Languages Haskell 101 Dr. Hyunyoung Lee 1 Contents 1. Historical Background of Haskell 2. Lazy, Pure, and Functional Language 3. Using ghc and ghci 4. Functions 5. Haskell Scripts

### Haskell through HUGS THE BASICS

Haskell through HUGS THE BASICS FP for DB Basic HUGS 1 Algorithmic Imperative Languages variables assignment if condition then action1 else action2 loop block while condition do action repeat action until

### Practical Haskell. An introduction to functional programming. July 21, Practical Haskell. Juan Pedro Villa-Isaza. Introduction.

Practical Practical An introduction to functional programming July 21, 2011 Contents Practical Practical is fun, and that s what it s all about! Even if seems strange to you at first, don t give up. Learning

### Haskell 101. (Version 1 (July 18, 2012)) Juan Pedro Villa Isaza

Haskell 101 (Version 1 (July 18, 2012)) Juan Pedro Villa Isaza Haskell 101: Contents Introduction Tutorial Homework Bibliography Haskell 101: Contents Introduction Tutorial Homework Bibliography Haskell

### CS 360: Programming Languages Lecture 12: More Haskell

CS 360: Programming Languages Lecture 12: More Haskell Geoffrey Mainland Drexel University Adapted from Brent Yorgey s course Introduction to Haskell. Section 1 Administrivia Administrivia Homework 5 due

### CSC312 Principles of Programming Languages : Functional Programming Language. Copyright 2006 The McGraw-Hill Companies, Inc.

CSC312 Principles of Programming Languages : Functional Programming Language Overview of Functional Languages They emerged in the 1960 s with Lisp Functional programming mirrors mathematical functions:

### An introduction to functional programming. July 23, 2010

An introduction to functional programming July 23, 2010 About Outline About About What is functional programming? What is? Why functional programming? Why? is novel. is powerful. is fun. About A brief

### Haskell Types, Classes, and Functions, Currying, and Polymorphism

1 CSCE 314: Programming Languages Dr. Flemming Andersen Haskell Types, Classes, and Functions, Currying, and Polymorphism 2 Types A type is a collection of related values. For example, Bool contains the

### CS 440: Programming Languages and Translators, Spring 2019 Mon

Haskell, Part 4 CS 440: Programming Languages and Translators, Spring 2019 Mon 2019-01-28 More Haskell Review definition by cases Chapter 6: Higher-order functions Revisit currying map, filter Unnamed

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

### INTRODUCTION TO FUNCTIONAL PROGRAMMING

INTRODUCTION TO FUNCTIONAL PROGRAMMING Graham Hutton University of Nottingham adapted by Gordon Uszkay 1 What is Functional Programming? Opinions differ, and it is difficult to give a precise definition,

### Haskell Introduction Lists Other Structures Data Structures. Haskell Introduction. Mark Snyder

Outline 1 2 3 4 What is Haskell? Haskell is a functional programming language. Characteristics functional non-strict ( lazy ) pure (no side effects*) strongly statically typed available compiled and interpreted

### Haskell Overview II (2A) Young Won Lim 9/26/16

(2A) Copyright (c) 2016 Young W. Lim. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later version published

### Programming Languages Fall 2013

Programming Languages Fall 2013 Lecture 2: types Prof. Liang Huang huang@qc.cs.cuny.edu Recap of Lecture 1 functional programming vs. imperative programming basic Haskell syntax function definition lazy

### Introduction. chapter Functions

chapter 1 Introduction In this chapter we set the stage for the rest of the book. We start by reviewing the notion of a function, then introduce the concept of functional programming, summarise the main

### CS 457/557: Functional Languages

CS 457/557: Functional Languages Lists and Algebraic Datatypes Mark P Jones Portland State University 1 Why Lists? Lists are a heavily used data structure in many functional programs Special syntax is

### CSC324- TUTORIAL 5. Shems Saleh* *Some slides inspired by/based on Afsaneh Fazly s slides

CSC324- TUTORIAL 5 ML Shems Saleh* *Some slides inspired by/based on Afsaneh Fazly s slides Assignment 1 2 More questions were added Questions regarding the assignment? Starting ML Who am I? Shems Saleh

### Haskell Overview II (2A) Young Won Lim 8/23/16

(2A) Copyright (c) 2016 Young W. Lim. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later version published

INTRODUCTION TO HASKELL PRINCIPLES OF PROGRAMMING LANGUAGES Norbert Zeh Winter 2018 Dalhousie University 1/81 HASKELL: A PURELY FUNCTIONAL PROGRAMMING LANGUAGE Functions are first-class values: Can be

### This example highlights the difference between imperative and functional programming. The imperative programming solution is based on an accumulator

1 2 This example highlights the difference between imperative and functional programming. The imperative programming solution is based on an accumulator (total) and a counter (i); it works by assigning

### CSCE 314 Programming Languages

CSCE 314 Programming Languages Final Review Part I Dr. Hyunyoung Lee 1 Programming Language Characteristics Different approaches to describe computations, to instruct computing devices E.g., Imperative,

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

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

Haskell Scripts Yan Huang yh33@indiana.edu Last Quiz Objectives Writing Haskell programs in.hs files Note some differences between programs typed into GHCi and programs written in script files Operator

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

### PROGRAMMING IN HASKELL. Chapter 5 - List Comprehensions

PROGRAMMING IN HASKELL Chapter 5 - List Comprehensions 0 Set Comprehensions In mathematics, the comprehension notation can be used to construct new sets from old sets. {x 2 x {1...5}} The set {1,4,9,16,25}

### CS 320: Concepts of Programming Languages

CS 320: Concepts of Programming Languages Wayne Snyder Computer Science Department Boston University Lecture 04: Basic Haskell Continued o Polymorphic Types o Type Inference with Polymorphism o Standard

### Functional Programming. Overview. Topics. Definition n-th Fibonacci Number. Graph

Topics Functional Programming Christian Sternagel Harald Zankl Evgeny Zuenko Department of Computer Science University of Innsbruck WS 2017/2018 abstract data types, algebraic data types, binary search

Haskell An Introduction What is Haskell? General purpose Purely functional No function can have side-effects IO is done using special types Lazy Strongly typed Polymorphic types Concise and elegant A First

### 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!

### CSE 3302 Programming Languages Lecture 8: Functional Programming

CSE 3302 Programming Languages Lecture 8: Functional Programming (based on the slides by Tim Sheard) Leonidas Fegaras University of Texas at Arlington CSE 3302 L8 Spring 2011 1 Functional Programming Languages

### Haskell: Lists. CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Friday, February 24, Glenn G.

Haskell: Lists CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Friday, February 24, 2017 Glenn G. Chappell Department of Computer Science University of Alaska Fairbanks

### CSC324 Principles of Programming Languages

CSC324 Principles of Programming Languages http://mcs.utm.utoronto.ca/~324 November 14, 2018 Today Final chapter of the course! Types and type systems Haskell s type system Types Terminology Type: set

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

### It is better to have 100 functions operate one one data structure, than 10 functions on 10 data structures. A. Perlis

Chapter 14 Functional Programming Programming Languages 2nd edition Tucker and Noonan It is better to have 100 functions operate one one data structure, than 10 functions on 10 data structures. A. Perlis

### Haskell 98 in short! CPSC 449 Principles of Programming Languages

Haskell 98 in short! n Syntax and type inferencing similar to ML! n Strongly typed! n Allows for pattern matching in definitions! n Uses lazy evaluation" F definition of infinite lists possible! n Has

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

### Lists. Michael P. Fourman. February 2, 2010

Lists Michael P. Fourman February 2, 2010 1 Introduction The list is a fundamental datatype in most functional languages. ML is no exception; list is a built-in ML type constructor. However, to introduce

PP 2017/18 Unit 11 Functional Programming with Haskell 1/37 Programming Paradigms Unit 11 Functional Programming with Haskell J. Gamper Free University of Bozen-Bolzano Faculty of Computer Science IDSE

### Lecture 2: List algorithms using recursion and list comprehensions

Lecture 2: List algorithms using recursion and list comprehensions Søren Haagerup Department of Mathematics and Computer Science University of Southern Denmark, Odense September 12, 2017 Expressions, patterns

### Higher Order Functions in Haskell

Higher Order Functions in Haskell Evan Misshula 2018-09-10 Outline Curried Functions Curried comparison Example partial application partial application of a string function Returned functions ZipWith flip

### Tuples. CMSC 330: Organization of Programming Languages. Examples With Tuples. Another Example

CMSC 330: Organization of Programming Languages OCaml 2 Higher Order Functions Tuples Constructed using (e1,..., en) Deconstructed using pattern matching Patterns involve parens and commas, e.g., (p1,p2,

### Defining Functions. CSc 372. Comparative Programming Languages. 5 : Haskell Function Definitions. Department of Computer Science University of Arizona

Defining Functions CSc 372 Comparative Programming Languages 5 : Haskell Function Definitions Department of Computer Science University of Arizona collberg@gmail.com When programming in a functional language

### CSc 372 Comparative Programming Languages

CSc 372 Comparative Programming Languages 8 : Haskell Function Examples Christian Collberg collberg+372@gmail.com Department of Computer Science University of Arizona Copyright c 2005 Christian Collberg

### CSc 372. Comparative Programming Languages. 8 : Haskell Function Examples. Department of Computer Science University of Arizona

1/43 CSc 372 Comparative Programming Languages 8 : Haskell Function Examples Department of Computer Science University of Arizona collberg@gmail.com Copyright c 2013 Christian Collberg Functions over Lists

### CSCE 314 Programming Languages

CSCE 314 Programming Languages Haskell: Declaring Types and Classes Dr. Hyunyoung Lee 1 Outline Declaring Data Types Class and Instance Declarations 2 Defining New Types Three constructs for defining types:

### CSci 4223 Principles of Programming Languages

CSci 4223 Principles of Programming Languages Lecture 11 Review Features learned: functions, tuples, lists, let expressions, options, records, datatypes, case expressions, type synonyms, pattern matching,

### Topic 7: Algebraic Data Types

Topic 7: Algebraic Data Types 1 Recommended Exercises and Readings From Haskell: The craft of functional programming (3 rd Ed.) Exercises: 5.5, 5.7, 5.8, 5.10, 5.11, 5.12, 5.14 14.4, 14.5, 14.6 14.9, 14.11,

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

### Functional Programming I *** Functional Programming and Interactive Theorem Proving. Ulrich Berger Michaelmas Term 2006

Functional Programming I *** Functional Programming and Interactive Theorem Proving Ulrich Berger Michaelmas Term 2006 2 *** Room 306 (Faraday Tower) Phone 513380 Fax 295708 u.berger@swansea.ac.uk http://www-compsci.swan.ac.uk/

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

### Intro to Haskell Notes: Part 5

Intro to Haskell Notes: Part 5 Adrian Brasoveanu October 5, 2013 Contents 1 Curried functions and related issues 1 1.1 Curried functions......................................... 1 1.2 Partially applied

### Programming with Math and Logic

.. Programming with Math and Logic an invitation to functional programming Ed Morehouse Wesleyan University The Plan why fp? terms types interfaces The What and Why of Functional Programming Computing

### 9/21/17. Outline. Expression Evaluation and Control Flow. Arithmetic Expressions. Operators. Operators. Notation & Placement

Outline Expression Evaluation and Control Flow In Text: Chapter 6 Notation Operator evaluation order Operand evaluation order Overloaded operators Type conversions Short-circuit evaluation of conditions

### CSCE 314 Programming Languages. Functional Parsers

CSCE 314 Programming Languages Functional Parsers Dr. Hyunyoung Lee 1 What is a Parser? A parser is a program that takes a text (set of tokens) and determines its syntactic structure. String or [Token]

### Processadors de Llenguatge II. Functional Paradigm. Pratt A.7 Robert Harper s SML tutorial (Sec II)

Processadors de Llenguatge II Functional Paradigm Pratt A.7 Robert Harper s SML tutorial (Sec II) Rafael Ramirez Dep Tecnologia Universitat Pompeu Fabra Paradigm Shift Imperative Paradigm State Machine

### 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:

### CMSC 330: Organization of Programming Languages. OCaml Expressions and Functions

CMSC 330: Organization of Programming Languages OCaml Expressions and Functions CMSC330 Spring 2018 1 Lecture Presentation Style Our focus: semantics and idioms for OCaml Semantics is what the language

### OCaml. ML Flow. Complex types: Lists. Complex types: Lists. The PL for the discerning hacker. All elements must have same type.

OCaml The PL for the discerning hacker. ML Flow Expressions (Syntax) Compile-time Static 1. Enter expression 2. ML infers a type Exec-time Dynamic Types 3. ML crunches expression down to a value 4. Value

### Principles of Programming Languages

Principles of Programming Languages h"p://www.di.unipi.it/~andrea/dida2ca/plp- 14/ Prof. Andrea Corradini Department of Computer Science, Pisa Introduc;on to Hakell Lesson 27! 1 The origins: ML programming

### Advanced Topics in Programming Languages Lecture 2 - Introduction to Haskell

Advanced Topics in Programming Languages Lecture 2 - Introduction to Haskell Ori Bar El Maxim Finkel 01/11/17 1 History Haskell is a lazy, committee designed, pure functional programming language that

### Conversion vs. Subtyping. Lecture #23: Conversion and Type Inference. Integer Conversions. Conversions: Implicit vs. Explicit. Object x = "Hello";

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). In Java, this is legal: Object x = "Hello";

### The Haskell HOP: Higher-order Programming

The Haskell HOP: Higher-order Programming COS 441 Slides 6 Slide content credits: Ranjit Jhala, UCSD Agenda Haskell so far: First-order functions This time: Higher-order functions: Functions as data, arguments

### Background. CMSC 330: Organization of Programming Languages. Useful Information on OCaml language. Dialects of ML. ML (Meta Language) Standard ML

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

### Programming Languages 3. Definition and Proof by Induction

Programming Languages 3. Definition and Proof by Induction Shin-Cheng Mu Oct. 22, 2015 Total Functional Programming The next few lectures concerns inductive definitions and proofs of datatypes and programs.

### CMSC 330: Organization of Programming Languages. Functional Programming with Lists

CMSC 330: Organization of Programming Languages Functional Programming with Lists CMSC330 Spring 2018 1 Lists in OCaml The basic data structure in OCaml Lists can be of arbitrary length Implemented as

### Solution sheet 1. Introduction. Exercise 1 - Types of values. Exercise 2 - Constructors

Solution sheet 1 Introduction Please note that there can be other solutions than those listed in this document. This is a literate Haskell file which is available as PDF, as well as literate Haskell source

### Parsing. Zhenjiang Hu. May 31, June 7, June 14, All Right Reserved. National Institute of Informatics

National Institute of Informatics May 31, June 7, June 14, 2010 All Right Reserved. Outline I 1 Parser Type 2 Monad Parser Monad 3 Derived Primitives 4 5 6 Outline Parser Type 1 Parser Type 2 3 4 5 6 What

### The List Datatype. CSc 372. Comparative Programming Languages. 6 : Haskell Lists. Department of Computer Science University of Arizona

The List Datatype CSc 372 Comparative Programming Languages 6 : Haskell Lists Department of Computer Science University of Arizona collberg@gmail.com All functional programming languages have the ConsList

### CPS 506 Comparative Programming Languages. Programming Language Paradigm

CPS 506 Comparative Programming Languages Functional Programming Language Paradigm Topics Introduction Mathematical Functions Fundamentals of Functional Programming Languages The First Functional Programming

### Lecture 4: Higher Order Functions

Lecture 4: Higher Order Functions Søren Haagerup Department of Mathematics and Computer Science University of Southern Denmark, Odense September 26, 2017 HIGHER ORDER FUNCTIONS The order of a function

### Programming Languages

CSE 130 : Winter 2013 Programming Languages Lecture 3: Crash Course, Datatypes Ranjit Jhala UC San Diego 1 Story So Far... Simple Expressions Branches Let-Bindings... Today: Finish Crash Course Datatypes

### Functional Programming for Logicians - Lecture 1

Functional Programming for Logicians - Lecture 1 Functions, Lists, Types Malvin Gattinger 4 June 2018 module L1 where Introduction Who is who Course website: https://malv.in/2018/funcproglog/ Malvin Gattinger

### Background Operators (1E) Young Won Lim 7/7/18

Background Operators (1E) Copyright (c) 2016-2018 Young W. Lim. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2

### FUNCTIONAL PROGRAMMING 1 HASKELL BASICS

1 FUNCTIONAL PROGRAMMING 1 HASKELL BASICS Dr. Ahmed Sallam Reference 2 Main: Introduction to Haskell Further By Brent Yorgey Functional Programming 3 Function is the atom of the language, and can be used

First Haskell Exercises CS110 November 23, 2016 Although it is possible to install Haskell on your computer, we want to get started quickly, so we will be using an online Haskell programming system (also

### Topic 1: Introduction

Recommended Exercises and Readings Topic 1: Introduction From Haskell: The craft of functional programming (3 rd Ed.) Readings: Chapter 1 Chapter 2 1 2 What is a Programming Paradigm? Programming Paradigm:

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

Functional Programming Language Haskell Mohammed Aslam CIS 24 Prof. Kopec Presentation: 03 Date: 05/05/2003 Haskell is a general purpose, purely functional programming language named after the logician

### The type checker will complain that the two branches have different types, one is string and the other is int

1 Intro to ML 1.1 Basic types Need ; after expression - 42 = ; val it = 42 : int - 7+1; val it = 8 : int Can reference it - it+2; val it = 10 : int - if it > 100 then "big" else "small"; val it = "small"

### Programming Languages Fall Prof. Liang Huang

Programming Languages Fall 2014 Prof. Liang Huang huang@qc.cs.cuny.edu Computer Science is no more about computers than astronomy is about telescopes. (Mis)attributed to Edsger Dijkstra, 1970. Computer

### Topic 5: Higher Order Functions

Topic 5: Higher Order Functions 1 Recommended Exercises and Readings From Haskell: The craft of functional programming (3 rd Ed.) Exercises: 10.1, 10.2, 10.3, 10.4, 10.5, 10.6, 10.7, 10.8, 10.9, 10.10,

### Topic 5: Higher Order Functions

Topic 5: Higher Order Functions 1 Recommended Exercises and Readings From Haskell: The craft of functional programming (3 rd Ed.) Exercises: 10.1, 10.2, 10.3, 10.4, 10.5, 10.6, 10.7, 10.8, 10.9, 10.10,