Topic 5: Higher Order Functions

Size: px
Start display at page:

Download "Topic 5: Higher Order Functions"

Transcription

1 Topic 5: Higher Order Functions 1

2 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, 10.13, 10.14, 10.15, 10.16, 10.27, 10.18, 10.19, 10.20, 10.21, 10.24, 10.25, 10.26, 11.7, 11.8, 11.9, 11.10, 11.19, 11.20, Readings: Chapter 10 Chapter 11.1, 11.2,

3 Functions We can visualize functions as a box Take some inputs Produce an output Inputs can be base types, tuples, lists, or Output can be a base type, tuple, list, or 3

4 Higher Order Functions In functional languages, the inputs and output can also be functions A function can take a function as a parameter A function can return a function as its result Higher order function: A function that takes one, or more, functions as a parameter and/or returns a function as its result 4

5 Higher Order Functions Passing a function to a function square :: Int > Int square n = n * n applytotuple :: (Int > Int) > (Int, Int, Int) > (Int, Int, Int) applytotuple f (a, b, c) = (f a, f b, f c) What s the result of applytotuple square (1, 2, 3)? 5

6 Higher Order Functions Write a function that computes a new list by applying a function to every element in a list First argument: The function to apply to each element Second argument: The list of elements to which the function is applied This operation is traditionally called map 6

7 Higher Order Functions Write a function that retains or discards items in a list First argument: A Boolean function Items that cause this function to return True will be retained Items that cause this function to return False will be discarded Second argument: The list of elements to which the function is applied This operation is traditionally called filter 7

8 Using Map and Filter Examples 8

9 Polymorphic Functions Polymorphic Function: A function that can be applied to multiple types of data Many functions in the Prelude module are polymorphic We can write our own polymorphic functions Ideally, we want one version of map that works for all data types, and one version of filter that works for all data types 9

10 Polymorphic Functions In Haskell: Polymorphic functions include one or more type variables in their type definition By convention, the type variables are lower case letters starting from a A function s type can include a mixture of base / list / tuple types and type variables 10

11 Polymorphic Functions Example: Rewrite myfilter so that it is polymorphic Do the input list and the result need to have the same type? What is the type of the function passed to mymap? 11

12 Polymorphic Functions Example: Rewrite mymap so that it is polymorphic Do the input list and the result need to have the same type? What is the type of the function passed to mymap? 12

13 Polymorphic Functions Example: Rewrite applytotuple so that it is polymorphic Do the input tuple and the result tuple need to have the same type? What is the type of the function passed to applytotuple? 13

14 Using Polymorphic Functions Assume the existence of the following functions: square :: Int > Int c2f :: Float > Float iseven :: Int > Bool plus :: Int > Int > Int map :: (a > b) > [a] > [b] filter :: (a > Bool) > [a] > [a] What is the result of the following expressions? map square [1.. 5] map c2f [ ] map plus [1.. 5] map iseven [1.. 5] filter iseven [1.. 5] filter square [1.. 5] 14

15 Folding Folding reduces a list to a single value by repeatedly applying a function to the value computed so far and the next item in the list Folding can occur from the left or the right Can be viewed as inserting an operator (function) between each value in the list Examples: Left folding (+) into the list [1..5] gives ((((1 + 2) + 3) + 4) + 5) Right folding min into the list [1..5] gives (1 `min` (2 `min` (3 `min` (4 `min` 5)))) This operation is also commonly referred to as reduce 15

16 Folding Write a function that performs a left fold on a list of values First parameter is the function to insert between each value in the list Second parameter is the list of values to process Questions to consider: What should left fold do if the list of values is empty? What should left fold do if the list of values has length 1? What should the type of the left fold function be? 16

17 Folding Write a function that performs a left fold on a list of values Write a function that performs a right fold on a list of values 17

18 Folding in Haskell The functions that we just wrote are referred to as foldl1 and foldr1 They only work on lists that contain at least one element More general functions foldl and foldr are also available foldl :: (b > a > b) > b > [a] > b foldr :: (a > b > b) > b > [a] > b The more general function can be safely applied to an empty list The identity element is returned 18

19 Folding Examples Use a fold to compute the sum of all of the items in a list Use a fold to compute the minimum value in a list Use a fold to reverse the elements in a list 19

20 Folding Examples Use a fold to remove adjacent duplicates from a list Use a fold to decode a run length encoded list 20

21 Folding Examples Use a fold to sort a list 21

22 Other Higher Order Functions zipwith Zip combines elements from two lists, forming pairs zipwith combines elements from two lists, performing an arbitrary operation zipwith :: (a > b > c) > [a] > [b] > [c] 22

23 Other Higher Order Functions Use zipwith and a fold to compute the dot product of two lists dotproduct [1, 2, 3, 4] [5, 6, 7, 8] evaluates to 1*5 + 2*6 + 3*7 + 4*8 = 70 23

24 Other Higher Order Functions sortby (in the Data.List module) sortby :: (a > a > Ordering) > [a] > [a] Ordering is a Haskell type with three possible values: LT GT EQ 24

25 Other Higher Order Functions Example: Use sortby to sort a list of strings The strings should be sorted in a case insensitive manner Hint: toupper :: Char > Char is available in the Data.Char module 25

26 Higher Order Functions Polymorphic higher order functions Each function can be used on lists of any type Each function takes a parameter that is a function Examples: map, filter, foldr, foldl, zipwith, sortby, Make it possible to perform some complex tasks without writing very much code 26

27 Lambda Functions Small (even tiny) helper functions are often needed when working with higher order functions Writing named helper functions can become tedious Lambda functions provide another mechanism for writing these functions Lambda functions are anonymous they don t get a name Lambda functions are defined inline 27

28 Lambda Functions Lambda Notation \ is used to represent the Greek character λ \ is immediately followed by the function s parameters > separates the parameters from the function s body Example: A function that sums two numbers \x y > x + y Example: A function that converts a string to uppercase \s > [toupper ch ch < s] Example: A function that determines whether or not an integer is even 28

29 Lambda Functions Use higher order functions and lambda functions to write one line expressions that Remove all of the odd numbers from a list Convert a list of temperatures in Celsius to a list of temperatures in Fahrenheit Square all of the even integers in a list, discard all the odd integers 29

30 Functions can Return Functions The value returned by a function can be a lambda expression Example: Create a function that takes a two parameter function as its only parameter and returns a new two parameter function as its result The new function will perform the same task, but its arguments will be in the opposite order This operation is commonly referred to as flip 30

31 Functions can Return Functions Example: Write a function that adjusts the capitalization of a string to match speech types of whisper, normal, and loud 31

32 Other Languages The concepts introduced here are not unique to Haskell Some other languages allow functions to operate on many different types of values Some other languages permit a function to be passed to another function or returned as a function s result Some other languages provide map, filter and reduce operations Some other languages provide all of these features 32

33 Polymorphic Functions in Other Languages Python C++ 33

34 Higher Order Functions in Other Languages How do we pass a function as a parameter to another function in Python 34

35 Higher Order Functions in Other Languages How do we pass a function as a parameter to another function in C++ 35

36 import java.util.arrays; import java.util.list; import java.util.stream.collectors; public class Higher { public static void main(string[] args) { List<String> names = Arrays.asList("Alice", "Bob", "Chantal", "Doug"); System.out.println("Names: " + names); List<String> yelled_names = names.stream().map(string::touppercase).collect(collectors.tolist()); System.out.println("Yelled names: " + yelled_names + "\n"); List<Integer> nums = Arrays.asList(1,2,3,4,5); System.out.println("Numbers: " + nums); Map, Filter and Fold in Other Languages Java provides map, filter and reduce methods And lambda functions that can be passed to them } List<Integer> squared = nums.stream().map(n > n * n).collect(collectors.tolist()); System.out.println("Squared numbers: " + squared + "\n"); } 36

37 Map, Filter and Fold in Other Languages Python provides map, filter and reduce functions map and filter are part of the standard module reduce must be imported from functools 37

38 Map, Filter and Fold in Other Languages C++ provides map, filter and reduce functions Actually provided as std::transform, std::copy_if and std::accumulate Need to include <algorithm> for std::transform and std::copy_if Need to include <numeric> for std::accumulate Need C++11 to use lambda functions 38

39 Summary Higher order functions take functions as parameters Or return them as the function s result Polymorphic functions operate on many different types of data Polymorphic higher order functions are powerful tools for manipulating data, often with a small amount of code Examples: map, filter, foldl / foldr, Lambda functions reduce the need to write separate small named helper functions These constructs are not unique to Haskell 39

Topic 5: Higher Order Functions

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,

More information

Topic 6: Partial Application, Function Composition and Type Classes

Topic 6: Partial Application, Function Composition and Type Classes Topic 6: Partial Application, Function Composition and Type Classes Recommended Exercises and Readings From Haskell: The craft of functional programming (3 rd Ed.) Exercises: 11.11, 11.12 12.30, 12.31,

More information

Topic 6: Partial Application, Function Composition and Type Classes

Topic 6: Partial Application, Function Composition and Type Classes Topic 6: Partial Application, Function Composition and Type Classes 1 Recommended Exercises and Readings From Haskell: The craft of functional programming (3 rd Ed.) Exercises: 11.11, 11.12 12.30, 12.31,

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

Higher Order Functions in Haskell

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

More information

Programming Paradigms

Programming Paradigms David Ng June 30, 2017 Contents 1 May 17, 2017 3 1.1 Programming Paradigm............................ 3 1.2 Languages.................................... 3 1.3 Haskell.....................................

More information

Topic 2: Making Decisions

Topic 2: Making Decisions Topic 2: Making Decisions 1 Recommended Exercises and Readings From Haskell: The craft of functional programming (3 rd Ed.) Exercises: 3.1, 3.5, 3.8, 3.9, 3.10, 3.11, 3.13, 3.14, 3.16, 3.17, 3.18, 3.19,

More information

Topic 7: Algebraic Data Types

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,

More information

Topic 2: Making Decisions

Topic 2: Making Decisions Recommended Exercises and Readings Topic 2: From Haskell: The craft of functional programming (3 rd Ed.) Exercises: 3.1, 3.5, 3.8, 3.9, 3.10, 3.11, 3.13, 3.14, 3.16, 3.17, 3.18, 3.19, 3.20, 3.22, 3.23

More information

Introduction to Programming, Aug-Dec 2006

Introduction to Programming, Aug-Dec 2006 Introduction to Programming, Aug-Dec 2006 Lecture 3, Friday 11 Aug 2006 Lists... We can implicitly decompose a list into its head and tail by providing a pattern with two variables to denote the two components

More information

Standard prelude. Appendix A. A.1 Classes

Standard prelude. Appendix A. A.1 Classes Appendix A Standard prelude In this appendix we present some of the most commonly used definitions from the standard prelude. For clarity, a number of the definitions have been simplified or modified from

More information

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

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

More information

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

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

More information

Topic 4: Tuples and Lists

Topic 4: Tuples and Lists Topic 4: Tuples and Lists 1 Recommended Exercises and Readings From Haskell: The craft of functional programming (3 rd Ed.) Exercises: 5.1, 5.2, 5.3, 5.15, 5.16, 5.17, 5.18, 5.19, 5.20, 5.21, 5.22, 5.23,

More information

CS 440: Programming Languages and Translators, Spring 2019 Mon

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

More information

CSCE 314 Programming Languages

CSCE 314 Programming Languages CSCE 314 Programming Languages Haskell: Higher-order Functions Dr. Hyunyoung Lee 1 Higher-order Functions A function is called higher-order if it takes a function as an argument or returns a function as

More information

Functional Programming Mid-term exam Tuesday 3/10/2017

Functional Programming Mid-term exam Tuesday 3/10/2017 Functional Programming Mid-term exam Tuesday 3/10/2017 Name: Student number: Before you begin: Do not forget to write down your name and student number above. If necessary, explain your answers in English.

More information

Shell CSCE 314 TAMU. Higher Order Functions

Shell CSCE 314 TAMU. Higher Order Functions 1 CSCE 314: Programming Languages Dr. Dylan Shell Higher Order Functions 2 Higher-order Functions A function is called higher-order if it takes a function as an argument or returns a function as a result.

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

Lecture 4: Higher Order Functions

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

More information

CS 360: Programming Languages Lecture 12: More 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

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

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

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

More information

EDAF40. 2nd June :00-19:00. WRITE ONLY ON ONE SIDE OF THE PAPER - the exams will be scanned in and only the front/ odd pages will be read.

EDAF40. 2nd June :00-19:00. WRITE ONLY ON ONE SIDE OF THE PAPER - the exams will be scanned in and only the front/ odd pages will be read. EDAF40 2nd June 2017 14:00-19:00 WRITE ONLY ON ONE SIDE OF THE PAPER - the exams will be scanned in and only the front/ odd pages will be read. DO NOT WRITE WITH OTHER COLOUR THAN BLACK - coloured text

More information

Hints: I used a left fold and wrote a named helper function when I created my solution.

Hints: I used a left fold and wrote a named helper function when I created my solution. 1) [4 marks] On a particular system, a password is considered acceptable if it meets the following constraints: It is at least 8 characters in length It contains at least one uppercase letter ('A' to 'Z')

More information

PROGRAMMING IN HASKELL. Chapter 2 - First Steps

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

More information

CS115 - Module 9 - filter, map, and friends

CS115 - Module 9 - filter, map, and friends Fall 2017 Reminder: if you have not already, ensure you: Read How to Design Programs, Intermezzo 3 (Section 18); Sections 19-23. Abstraction abstraction, n. 3a.... The process of isolating properties or

More information

A tour of the Haskell Prelude

A tour of the Haskell Prelude A tour of the Haskell Prelude Bernie Pope 2001 1 Haskell The Haskell language was conceived during a meeting held at the 1987 Functional Programming and Computer Architecture conference (FPCA 87). At the

More information

Haskell An Introduction

Haskell An Introduction 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

More information

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

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

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

A general introduction to Functional Programming using Haskell

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

More information

Haskell 98 in short! CPSC 449 Principles of Programming Languages

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

More information

Exercises on ML. Programming Languages. Chanseok Oh

Exercises on ML. Programming Languages. Chanseok Oh Exercises on ML Programming Languages Chanseok Oh chanseok@cs.nyu.edu Dejected by an arcane type error? - foldr; val it = fn : ('a * 'b -> 'b) -> 'b -> 'a list -> 'b - foldr (fn x=> fn y => fn z => (max

More information

CS242 COMPUTER PROGRAMMING

CS242 COMPUTER PROGRAMMING CS242 COMPUTER PROGRAMMING I.Safa a Alawneh Variables Outline 2 Data Type C++ Built-in Data Types o o o o bool Data Type char Data Type int Data Type Floating-Point Data Types Variable Declaration Initializing

More information

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

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

More information

Functional Programming in C++

Functional Programming in C++ Functional Programming in C++ David Letscher Saint Louis University Programming Languages Letscher (SLU) Functional Programming in C++ Prog Lang 1 / 17 What is needed to incorporate functional programming?

More information

Functional abstraction. What is abstraction? Eating apples. Readings: HtDP, sections Language level: Intermediate Student With Lambda

Functional abstraction. What is abstraction? Eating apples. Readings: HtDP, sections Language level: Intermediate Student With Lambda Functional abstraction Readings: HtDP, sections 19-24. Language level: Intermediate Student With Lambda different order used in lecture section 24 material introduced much earlier sections 22, 23 not covered

More information

Functional abstraction

Functional abstraction Functional abstraction Readings: HtDP, sections 19-24. Language level: Intermediate Student With Lambda different order used in lecture section 24 material introduced much earlier sections 22, 23 not covered

More information

Lecture 2: List algorithms using recursion and list comprehensions

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

More information

Functional Programming TDA 452, DIT 142

Functional Programming TDA 452, DIT 142 Chalmers Göteborgs Universitet 2016-04-07 Examiner: David Sands dave@chalmers.se. Answering questions on the day of the exam (at approx 15.00): Gregoire Detrez (tel: 073 55 69 550) and at other times by

More information

Part 2: Programming Questions

Part 2: Programming Questions Part 2: Programming Questions This part of the exam is open book / open Internet, with the caveat that you must not communicate with anyone else. This means that while you are welcome to look something

More information

Topic 8: Lazy Evaluation

Topic 8: Lazy Evaluation Topic 8: Lazy Evaluation 1 Recommended Exercises and Readings From Haskell: The craft of functional programming (3 rd Ed.) Exercises: 17.1, 17.2, 17.4, 17.8, 17.23, 17.25, 17.28, 17.29 Readings: Chapter

More information

Haskell Types COMP360

Haskell Types COMP360 Haskell Types COMP360 No computer has ever been designed that is ever aware of what it's doing; but most of the time, we aren't either. Marvin Minsky Haskell Programming Assignment A Haskell programming

More information

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

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

More information

CSC324 Principles of Programming Languages

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

More information

CSE 3302 Programming Languages Lecture 8: Functional Programming

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

More information

PROGRAMMING IN HASKELL. Chapter 5 - List Comprehensions

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}

More information

Type-indexed functions in Generic Haskell

Type-indexed functions in Generic Haskell Type-indexed functions in Generic Haskell Johan Jeuring September 15, 2004 Introduction Today I will talk about: a Types of polymorphism. b Type-indexed functions. c Dependencies. Read about b, and c in

More information

INTRODUCTION TO HASKELL

INTRODUCTION TO HASKELL 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

More information

Topic 9: Type Checking

Topic 9: Type Checking Recommended Exercises and Readings Topic 9: Type Checking From Haskell: The craft of functional programming (3 rd Ed.) Exercises: 13.17, 13.18, 13.19, 13.20, 13.21, 13.22 Readings: Chapter 13.5, 13.6 and

More information

Topic 9: Type Checking

Topic 9: Type Checking Topic 9: Type Checking 1 Recommended Exercises and Readings From Haskell: The craft of functional programming (3 rd Ed.) Exercises: 13.17, 13.18, 13.19, 13.20, 13.21, 13.22 Readings: Chapter 13.5, 13.6

More information

HIGHER-ORDER FUNCTIONS

HIGHER-ORDER FUNCTIONS 5 HIGHER-ORDER FUNCTIONS Haskell functions can take functions as parameters and return functions as return values. A function that does either of these things is called a higher-order function. Higher-order

More information

Haskell Programs. Haskell Fundamentals. What are Types? Some Very Basic Types. Types are very important in Haskell:

Haskell Programs. Haskell Fundamentals. What are Types? Some Very Basic Types. Types are very important in Haskell: Haskell Programs We re covering material from Chapters 1-2 (and maybe 3) of the textbook. Haskell Fundamentals Prof. Susan Older A Haskell program is a series of comments and definitions. Each comment

More information

Functional Programming for Logicians - Lecture 1

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

More information

Fall 2018 Discussion 8: October 24, 2018 Solutions. 1 Introduction. 2 Primitives

Fall 2018 Discussion 8: October 24, 2018 Solutions. 1 Introduction. 2 Primitives CS 6A Scheme Fall 208 Discussion 8: October 24, 208 Solutions Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write

More information

Lecture 10 September 11, 2017

Lecture 10 September 11, 2017 Programming in Haskell S P Suresh http://www.cmi.ac.in/~spsuresh Lecture 10 September 11, 2017 Combining elements sumlist :: [Int] -> Int sumlist [] = 0 sumlist (x:xs) = x + (sumlist xs) multlist :: [Int]

More information

Using Strategies for Assessment of Functional Programming Exercises

Using Strategies for Assessment of Functional Programming Exercises Using Strategies for Assessment of Functional Programming Exercises Ir. Alex Gerdes Joint work with prof. dr. Johan Jeuring and dr. Bastiaan Heeren Open Universiteit Nederland School of Computer Science

More information

Parallel Haskell on MultiCores and Clusters

Parallel Haskell on MultiCores and Clusters Parallel Haskell on MultiCores and Clusters (part of Advanced Development Techniques) Hans-Wolfgang Loidl School of Mathematical and Computer Sciences Heriot-Watt University, Edinburgh (presented at the

More information

FUNCTIONAL PROGRAMMING NO.9 TYPE AND CLASS. Tatsuya Hagino

FUNCTIONAL PROGRAMMING NO.9 TYPE AND CLASS. Tatsuya Hagino 1 FUNCTIONAL PROGRAMMING NO.9 TYPE AND CLASS Tatsuya Hagino hagino@sfc.keio.ac.jp 2 Static Type Checking and Type Inference Type a set of values Bool = { True, False } Char = { 'a', 'b',... } Int = {...

More information

Types, lists & functions

Types, lists & functions Week 2 Types, lists & functions Data types If you want to write a program that allows the user to input something, you can use the command input: name = input (" What is your name? ") print (" Hello "+

More information

(ii) Define a function ulh that takes a list xs, and pairs each element with all other elements in xs.

(ii) Define a function ulh that takes a list xs, and pairs each element with all other elements in xs. EXAM FUNCTIONAL PROGRAMMING Tuesday the 1st of October 2016, 08.30 h. - 10.30 h. Name: Student number: Before you begin: Do not forget to write down your name and student number above. If necessary, explain

More information

Functional Programming in Haskell for A level teachers

Functional Programming in Haskell for A level teachers Functional Programming in Haskell for A level teachers About this document Functional Programming is now part of the A level curriculum. This document is intended to get those who already have some programming

More information

COMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette

COMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette COMP 250: Java Programming I Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette Variables and types [Downey Ch 2] Variable: temporary storage location in memory.

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 04: Basic Haskell Continued o Polymorphic Types o Type Inference with Polymorphism o Standard

More information

Shell CSCE 314 TAMU. Haskell Functions

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

More information

Java Identifiers, Data Types & Variables

Java Identifiers, Data Types & Variables Java Identifiers, Data Types & Variables 1. Java Identifiers: Identifiers are name given to a class, variable or a method. public class TestingShastra { //TestingShastra is an identifier for class char

More information

Programming Language Concepts: Lecture 14

Programming Language Concepts: Lecture 14 Programming Language Concepts: Lecture 14 Madhavan Mukund Chennai Mathematical Institute madhavan@cmi.ac.in http://www.cmi.ac.in/~madhavan/courses/pl2009 PLC 2009, Lecture 14, 11 March 2009 Function programming

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

Review Chapter 6 in Bravaco. Short Answers 1. This type of method does not return a value. a. null b. void c. empty d. anonymous

Review Chapter 6 in Bravaco. Short Answers 1. This type of method does not return a value. a. null b. void c. empty d. anonymous Assignment 3 Methods Review CSC 123 Fall 2018 Notes: All homework must be submitted via e-mail. All parts of assignment must be submitted in a single e-mail with multiple attachments when required. Notes:

More information

Haskell through HUGS THE BASICS

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

More information

Fundamentals of Programming Data Types & Methods

Fundamentals of Programming Data Types & Methods Fundamentals of Programming Data Types & Methods By Budditha Hettige Overview Summary (Previous Lesson) Java Data types Default values Variables Input data from keyboard Display results Methods Operators

More information

Topics: Material through example 19 (types, operators, expressions, functions, selection, loops, arrays)

Topics: Material through example 19 (types, operators, expressions, functions, selection, loops, arrays) CPSC 122 Study Guide: Examination 1 Topics: Material through example 19 (types, operators, expressions, functions, selection, loops, arrays) 1. What is the output? int x, y; x = y = 0; while(x < 5) y +=

More information

C212 Early Evaluation Exam Mon Feb Name: Please provide brief (common sense) justifications with your answers below.

C212 Early Evaluation Exam Mon Feb Name: Please provide brief (common sense) justifications with your answers below. C212 Early Evaluation Exam Mon Feb 10 2014 Name: Please provide brief (common sense) justifications with your answers below. 1. What is the type (and value) of this expression: 5 * (7 + 4 / 2) 2. What

More information

Scheme Quick Reference

Scheme Quick Reference Scheme Quick Reference COSC 18 Fall 2003 This document is a quick reference guide to common features of the Scheme language. It is not intended to be a complete language reference, but it gives terse summaries

More information

CS 209 Functional Programming

CS 209 Functional Programming CS 209 Functional Programming Lecture 03 - Intro to Monads Dr. Greg Lavender Department of Computer Science Stanford University "The most important thing in a programming language is the name. A language

More information

CS 455 Midterm Exam 1 Fall 2016 [Bono] Thursday, Sept. 29, 2016

CS 455 Midterm Exam 1 Fall 2016 [Bono] Thursday, Sept. 29, 2016 Name: USC NetID (e.g., ttrojan): CS 455 Midterm Exam 1 Fall 2016 [Bono] Thursday, Sept. 29, 2016 There are 5 problems on the exam, with 56 points total available. There are 10 pages to the exam (5 pages

More information

Logical Methods in... using Haskell Getting Started

Logical Methods in... using Haskell Getting Started Logical Methods in... using Haskell Getting Started Jan van Eijck May 4, 2005 Abstract The purpose of this course is to teach a bit of functional programming and logic, and to connect logical reasoning

More information

CSc 372. Comparative Programming Languages. 11 : Haskell Higher-Order Functions. Department of Computer Science University of Arizona

CSc 372. Comparative Programming Languages. 11 : Haskell Higher-Order Functions. Department of Computer Science University of Arizona CSc 372 Comparative Programming Languages 11 : Haskell Higher-Order Functions Department of Computer Science University of Arizona collberg@gmail.com Copyright c 2010 Christian Collberg Higher-Order Functions

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

CSc 520 Principles of Programming Languages. Currying Revisited... Currying Revisited. 16: Haskell Higher-Order Functions

CSc 520 Principles of Programming Languages. Currying Revisited... Currying Revisited. 16: Haskell Higher-Order Functions Higher-Order Functions CSc 520 Principles of Programming Languages 16: Haskell Higher-Order Functions Christian Collberg collberg@cs.arizona.edu Department of Computer Science University of Arizona Copyright

More information

Chapter 15. Functional Programming. Topics. Currying. Currying: example. Currying: example. Reduction

Chapter 15. Functional Programming. Topics. Currying. Currying: example. Currying: example. Reduction Topics Chapter 15 Functional Programming Reduction and Currying Recursive definitions Local definitions Type Systems Strict typing Polymorphism Classes Booleans Characters Enumerations Tuples Strings 2

More information

Box-and-arrow Diagrams

Box-and-arrow Diagrams Box-and-arrow Diagrams 1. Draw box-and-arrow diagrams for each of the following statements. What needs to be copied, and what can be referenced with a pointer? (define a ((squid octopus) jelly sandwich))

More information

Scheme Quick Reference

Scheme Quick Reference Scheme Quick Reference COSC 18 Winter 2003 February 10, 2003 1 Introduction This document is a quick reference guide to common features of the Scheme language. It is by no means intended to be a complete

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

Functional Programming in Haskell Part I : Basics

Functional Programming in Haskell Part I : Basics Functional Programming in Haskell Part I : Basics Madhavan Mukund Chennai Mathematical Institute 92 G N Chetty Rd, Chennai 600 017, India madhavan@cmi.ac.in http://www.cmi.ac.in/ madhavan Madras Christian

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 06: Useful Haskell Syntax, HO Programming Continued o Goodbye to Bare Bones Haskell: Built-in

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

CSC 372 Haskell Mid-term Exam Feburary 28, 2014

CSC 372 Haskell Mid-term Exam Feburary 28, 2014 Last name, NetID CSC 372 Haskell Mid-term Exam Feburary 28, 2014 READ THIS FIRST Read this page now but do not turn this page until you are told to do so. Go ahead and fill in your last name and NetID

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 08: Type Classes o o Review: What is a type class? Basic Type Classes: Eq, Ord, Enum, Integral,

More information

Programming. We will be introducing various new elements of Python and using them to solve increasingly interesting and complex problems.

Programming. We will be introducing various new elements of Python and using them to solve increasingly interesting and complex problems. Plan for the rest of the semester: Programming We will be introducing various new elements of Python and using them to solve increasingly interesting and complex problems. We saw earlier that computers

More information

More on methods and variables. Fundamentals of Computer Science Keith Vertanen

More on methods and variables. Fundamentals of Computer Science Keith Vertanen More on methods and variables Fundamentals of Computer Science Keith Vertanen Terminology of a method Goal: helper method than can draw a random integer between start and end (inclusive) access modifier

More information

Informatics 1 Functional Programming Lecture 7. Map, filter, fold. Don Sannella University of Edinburgh

Informatics 1 Functional Programming Lecture 7. Map, filter, fold. Don Sannella University of Edinburgh Informatics 1 Functional Programming Lecture 7 Map, filter, fold Don Sannella University of Edinburgh Part I Map Squares *Main> squares [1,-2,3] [1,4,9] squares :: [Int] -> [Int] squares xs [ x*x x

More information

Functional Programming in Java Part 2. CSE 219 Department of Computer Science, Stony Brook University

Functional Programming in Java Part 2. CSE 219 Department of Computer Science, Stony Brook University Functional Programming in Java Part 2 CSE 219, Stony Brook University Functions as Objects The interface java.util.function.function To store a function (i.e., take a single argument and returns a

More information

Programming Problems 22nd Annual Computer Science Programming Contest

Programming Problems 22nd Annual Computer Science Programming Contest Programming Problems 22nd Annual Computer Science Programming Contest Department of Mathematics and Computer Science Western Carolina University 5 April 2011 Problem One: Add Times Represent a time by

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

Symbolic Computation and Common Lisp

Symbolic Computation and Common Lisp Symbolic Computation and Common Lisp Dr. Neil T. Dantam CSCI-56, Colorado School of Mines Fall 28 Dantam (Mines CSCI-56) Lisp Fall 28 / 92 Why? Symbolic Computing: Much of this course deals with processing

More information

CSC324 Principles of Programming Languages

CSC324 Principles of Programming Languages CSC324 Principles of Programming Languages http://mcs.utm.utoronto.ca/~324 November 21, 2018 Last Class Types terminology Haskell s type system Currying Defining types Value constructors Algebraic data

More information

Haskell: yet another Functional Language. Distributed and Parallel Technology

Haskell: yet another Functional Language. Distributed and Parallel Technology Distributed and Parallel Technology Introducing Haskell Hans-Wolfgang Loidl http://www.macs.hw.ac.uk/~hwloidl School of Mathematical and Computer Sciences Heriot-Watt University, Edinburgh Haskell: yet

More information

PROGRAMMING IN HASKELL. CS Chapter 6 - Recursive Functions

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

More information