CS 360: Programming Languages Lecture 12: More Haskell

Size: px
Start display at page:

Download "CS 360: Programming Languages Lecture 12: More Haskell"

Transcription

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

2 Section 1 Administrivia

3 Administrivia Homework 5 due Monday night (February 27). Homework 5 includes tests you can run automatically with make run-tests. Please use them! Code that does not compile will receive a zero. You can make sure that your code compiles by typing make.

4 Section 2 More Haskell

5 Pattern Matching Syntax The general syntax for pattern matching is: pat ::= _ var var@pat Constructor pat 1 pat 2... pat n (pat) area :: Shape -> Double area (Circle r) = pi * r ^ 2 area (Rectangle x1 y1 x2 y2) = abs (x2 - x1) * abs (y2 - y1) firstcircle :: [Shape] -> Shape firstcircle [] = error "Urk!" firstcircle (shape@(circle _) : _) = shape firstcircle (_:shapes) = firstcircle shapes

6 Case Expressions The fundamental Haskell construct for pattern matching is the case expression. In general, a case expression looks like this: case exp of pat1 -> exp1 pat2 -> exp2... In fact, the multi-clause syntax for defining functions that we have seen is just syntactic sugar for a case expression. Instead of this area :: Shape -> Double area (Circle r) = pi * r ^ 2 area (Rectangle x1 y1 x2 y2) = abs (x2 - x1) * abs (y2 - y1) we could have written this area :: Shape -> Double area shape = case shape of (Circle r) -> pi * r ^ 2 (Rectangle x1 y1 x2 y2) -> abs (x2 - x1) * abs (y2 - y1)

7 Tuples There is one more pervasive data type we haven t mentioned: tuples. Tuples have a single data constructor, which has a fixed arity, i.e., number of fields. There is also special syntax for tuples. anintpair :: (Int, Int) anintpair = (3, 4)

8 Records It is often convenient to refer to field of a data constructor by name. radius :: Shape -> Double radius (Circle r) = r radius (Rectangle ) = error "urk!" Haskell provides syntax for defining and matching on records. data Shape = Circle { centx :: Double, centy :: Double, radius :: Double} Rectangle { ulx :: Double, uly :: Double, urx :: Double, ury :: Double } mycircle = Circle myothercircle = Circle { centx = 0, centy = 0, radius = 1 } radiusof circle = radius circle area (Circle { radius = r }) = pi * r ^ 2 area (Rectangle { ulx = x1, uly = y1, urx = x2, ury = y2 }) = abs (x2 - x1) * abs (y2 - y1)

9 Polymorphism Remember this function from the first lecture? id x = x What type do you think it has? What (not whom) can we ask? The function id has type t -> t. Here, t is a type variable. Just as variables abstract over values, type variables abstract over types.

10 A safe head function In Haskell, the head function raises an error and aborts execution if you give it the empty list. Let s try it. It would be nice to define a safehead that doesn t raise an error, but somehow returns a value that indicates something went wrong. Let s try to define a function safeheadints that works for lists of Ints. We will need a new data type that lets us differentiate between a normal result and the error case. data MaybeHead = NoHead JustHead Int Now, how can we write safeheadints? Let s try. safeheadints :: [Int] -> MaybeHead safeheadints [] = NoHead safeheadints (x:_) = JustHead x

11 Generalizing safehead But what about lists of characters? Or lists of strings? Or lists of lists of integers? We can abstract over the type of data by using a type variable! Instead of this: data MaybeHead = NoHead JustHead Int we want this: data Maybe a = Nothing Just a Now, how can we write safehead? safehead :: [a] -> Maybe a safehead [] = Nothing safehead (x:_) = Just x

12 Polymorphism The function safehead is polymorphic it can operate on a list containing values of any type. One important thing to note about polymorphic functions is that the caller gets to pick the types. When you write a polymorphic function, it must work for every possible input type. Why is the following function bogus? bogus :: Maybe a -> Bool bogus (Just 'x') = True bogus _ = False This functions assumes that the type a is Char the function doesn t make sense for any value of the type variable a, but only when a is Char.

13 Parametric Polymorphism On the other hand, this function is perfectly fine isjust :: Maybe a -> Bool isjust Nothing = False isjust (Just _) = True isjust works for any value of the type variable a it doesn t care what a is. The not caring is what the parametric in parametric polymorphism means. A function that is parametrically polymorphic in a can t do one thing when a is Int and a different thing when a is Bool Haskell simply provides no facility for writing such an operation. This property of a language is called parametricity.

14 Consequences of Parametricity Parametricity has many deep consequences. One consequence is something called type erasure. Because a running Haskell program can never make decisions based on type information, all the type information can be dropped during compilation. Though types are very important when writing and compiling Haskell code, they are completely irrelevant when running Haskell code. This property gives Haskell (and other statically typed languages) a huge speed boost when compared to other languages, such as Python, that need to keep types around at runtime.

15 Consequences of Parametricity Parametricity also restricts what functions you can write and lets you draw conclusions about a function knowing only its type. Consider the type signature for strange. How could you write this function? strange :: a -> b The strange function takes a value of some type a and produces a value of another type b. Remember, the caller gets to pick a and b. There is no way to write strange! strange = error "impossible!"

16 Consequences of Parametricity cont d What do you think this function does? limited :: a -> a This function must produce a value of type a when given a value of type a. There is only one way to do this, so its definition must be: limited x = x That is, if a function has type a -> a, it must be the identity function! One small catch...it could also call error or always enter an infinite loop.

17 List Exercises The first thing you should do when writing a function in Haskell is write down its type signature. Write map in Haskell. Write append in Haskell. Write take in Haskell. take n l should return the first n elements of the list l. Write drop in Haskell. drop n l should return the list l, but with the first n elements removed. Define a List data type that can contain any type of element.

18 Modules in Haskell Haskell has an extensive standard library, called the Prelude. Haskell libraries are distributed as packages, which contain one or more modules. Functions can be imported from modules like this: import Data.Char (toupper) This imports the toupper function from the Data.Char module. The parenthesized bit is optional; if it is left out, all definitions from the imported module are brought in. Read LYAH Chapter 7 for more information on modules.

19 Total and partial functions Consider this polymorphic type: [a] -> a. What function(s) could have this type? The Prelude function head has this type. Let s look at its source: head :: [a] -> a head (x:_) = x head [] = error "Prelude.head: empty list" It crashes on the empty list! There is no way to make up a value of an arbitrary type a, so head must crash. The function head is a partial function. Functions which are well-defined on all possible inputs are known as total functions. It is good practice to avoid partial functions in any language. This tends to be easier in Haskell than in other languages.

20 Replacing partial functions Partial functions like head and tail can usually be replaced by pattern matching. Consider the two following functions: dostuff1 :: [Int] -> Int dostuff1 [] = 0 dostuff1 [_] = 0 dostuff1 xs = head xs + (head (tail xs)) dostuff2 :: [Int] -> Int dostuff2 [] = 0 dostuff2 [_] = 0 dostuff2 (x1:x2:_) = x1 + x2 Both functions compute the same value, but only the second is obviously total. It is also much easier to read.

21 Replacing partial functions cont d Recall our function safehead safehead :: [a] -> Maybe a safehead [] = Nothing safehead (x:_) = Just x What if we know we will only use head in situations where we are guaranteed to have a non-empty list? Then we should encode this knowledge in the types we use! Let s write such a type.

22 Important Lessons About Types Types are invariants. Consequence: We can use types to encode invariants about programs. These invariants are checked by the compiler at compile time. Dependently typed languages have even stronger type systems that can encode arbitrary invariants. Advice: Always write down a type signature first.

23 Higher-order Functions in Haskell We have already seen higher-order functions like map in Haskell. Haskell programmers tend to use higher-order functions more often than many other programmers. Let s try our hand at writing a few... Notice the syntax for defining operators using prefix notation. You can read about this in LYAH Chapter 6. Why do we define $? Because ($) is parsed as an operator, and this is useful for avoiding parentheses. For example, instead of this negatenumevens1 :: [Int] -> Int negatenumevens1 x = negate (length (filter even x)) we can write this negatenumevens2 :: [Int] -> Int negatenumevens2 x = negate $ length $ filter even x Just as in Scheme, we can write anonymous functions in Haskell using lambdas. The syntax is: id :: a -> a id = \x -> x

24 Type Classes in Haskell We have seen parametric polymorphism. A polymorphic function like length :: [a] -> Int works for any type a. Sometimes we want functions to work for several types, but not all types. A great example of this is (+) we want to be able to add Ints and Integers and Doubles, but not Maybe Chars. This form of polymorphism is called ad-hoc polymorphism. A Haskell type class defines a set of operations. We can then choose several types that support those operations via class instances. These are not the same as object-oriented classes and instances! Intuitively, type classes correspond to sets of types which have certain operations defined for them.

25 The Eq Type Class Let s look at the Eq type class provided by the Prelude. class Eq a where (==) :: a -> a -> Bool (/=) :: a -> a -> Bool We can read this as follows: Eq is declared to be a type class with a single (type) parameter, a. Any type a which wants to be an instance of Eq must define two functions, (==) and (/=), with the indicated type signatures. For example, to make Int an instance of Eq, we would have to define (==) :: Int -> Int -> Bool and (/=) :: Int -> Int -> Bool. We don t actually need to do this since this instance of the type class Eq for the type Int is part of the Prelude.

26 Type Class Constraints Let s look at the type of (==): (==) :: Eq a => a -> a -> Bool The Eq a that comes before the => is a type class constraint. This constraint says that for any type a that is an instance of Eq, (==) can take two values of type a and return a Bool. It is a type error to call the function (==) on some type which is not an instance of Eq. A normal polymorphic type is a promise that the function will work for whatever type the caller chooses. A type with a type class constraint is a restricted promise that the function will work for any type the caller chooses, as long as the chosen type is an instance of the required type class(es). When (==) (or any type class method) is used, the compiler uses type inference to figure out which implementation of (==) should be chosen based on the inferred types of its arguments.

27 Defining an Instance Let s define an instance of Eq for the following type: data Foo = F Int G Char It s a bit annoying that we have to define both (==) and (/=). Fortunately, type classes can give default implementations of methods in terms of other methods, which should be used whenever an instance does not override the default definition with its own. The actual definition of Eq is: class Eq a where (==), (/=) :: a -> a -> Bool x == y = not (x /= y) x /= y = not (x == y) This means we can define either (==) or (/=) the other one will be automatically defined in terms of the one we specify. However, we have to be careful: if we don t specify either one, we get infinite recursion!

28 Automatic Deriving As it turns out, Eq and a few other standard type classes are special: GHC is able to automatically generate instances of these classes for us. For our data type Foo, we can request that GHC automatically construct instances like this so: data Foo = F Int G Char deriving (Eq, Ord, Show) This tells GHC to automatically derive instances of the Eq, Ord, and Show type classes for our data type Foo. This deriving mechanism is baked into Haskell you can t make your own class and tell GHC how to derive instances. The full list of derivable classes is Eq, Ord, Enum, Ix, Bounded, Show, and Read. See the GHC manual for details if you re interested.

29 Standard type classes Ord is for types whose elements can be totally ordered, that is, where any two elements can be compared to see which is less than the other. It provides comparison operations like (<) and (<=), and also the compare function. Num is for numeric types, which support things like addition, subtraction, and multiplication. One very important thing to note is that integer literals are actually type class polymorphic: Prelude> :t 5 5 :: Num a => a This means that literals like 5 can be used as Ints, Integers, Doubles, or any other type which is an instance of Num (Rational, Complex Double, or even a type you define...) Show defines the method show, which is used to convert values into Strings. Read is the dual of Show. Integral represents whole number types such as Int and Integer.

30 Haskell Class vs. Java Interfaces Haskell s type classes are similar to Java interfaces. Both define a set of types/classes which implement a specified list of operations. However, Haskell type classes are more general than Java interfaces. When a Java class is defined, any interfaces it implements must be declared. Type class instances are declared separately from the declaration of the corresponding types and can even be put in a separate module.

31 Haskell Class vs. Java Interfaces cont d Haskell type classes can easily handle binary (or ternary, or...) methods, as in class Num a where (+) :: a -> a -> a... There is no nice way to do this in Java: for one thing, one of the two arguments would have to be the privileged one which is actually getting the (+) method invoked on it, and this asymmetry is awkward. Java s subtyping means receiving two arguments of a certain interface type does not guarantee that they are actually the same type, making implementing binary operators such as (+) awkward (usually requiring some runtime type checks).

32 Haskell Class vs. Java Interfaces cont d Haskell also supports multi-parameter type classes. For example, consider a hypothetical type class class Blerg a b where blerg :: a -> b -> Bool Using blerg amounts to doing multiple dispatch: which implementation of blerg the compiler should choose depends on both the types a and b. There is no easy way to do this in Java.

33 Implementing a Set data type Let s implement a simple abstract data type: sets. Question: what options are there for representing sets? We will represent sets as sorted lists with no duplicates. Question: can we write a Haskell type that expresses the invariant that a list is sorted? Let s get to work... P(Q), the power set of Q, is the set of all subsets of Q including the empty set and the set Q itself. Question: if Q contains n elements, how many elements are in P(Q)? Hint: use induction.

CS 360: Programming Languages Lecture 10: Introduction to Haskell

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

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

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

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

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

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

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

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

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

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

More information

Overloading, Type Classes, and Algebraic Datatypes

Overloading, Type Classes, and Algebraic Datatypes Overloading, Type Classes, and Algebraic Datatypes Delivered by Michael Pellauer Arvind Computer Science and Artificial Intelligence Laboratory M.I.T. September 28, 2006 September 28, 2006 http://www.csg.csail.mit.edu/6.827

More information

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

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

More information

Programming with Math and Logic

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

More information

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

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

More information

Programming Languages Fall 2013

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

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

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

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

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

More information

CIS 194: Homework 4. Due Wednesday, February 18, What is a Number?

CIS 194: Homework 4. Due Wednesday, February 18, What is a Number? CIS 194: Homework 4 Due Wednesday, February 18, 2015 What is a Number? This may sound like a deep, philosophical question, but the Haskell type system gives us a simple way to answer it. A number is any

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

Structural polymorphism in Generic Haskell

Structural polymorphism in Generic Haskell Structural polymorphism in Generic Haskell Andres Löh andres@cs.uu.nl 5 February 2005 Overview About Haskell Genericity and other types of polymorphism Examples of generic functions Generic Haskell Overview

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

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

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:

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

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

Course year Typeclasses and their instances

Course year Typeclasses and their instances Course year 2016-2017 Typeclasses and their instances Doaitse Swierstra and Atze Dijkstra with extra s Utrecht University September 29, 2016 1. The basics 2 Overloading versus parametric polymorphism 1

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

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

CSCE 314 Programming Languages

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:

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

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

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

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

More information

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

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

More information

Functional Programming. Overview. Topics. Recall λ-terms. Examples

Functional Programming. Overview. Topics. Recall λ-terms. Examples 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

More information

CS 457/557: Functional Languages

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

More information

CS558 Programming Languages

CS558 Programming Languages CS558 Programming Languages Fall 2017 Lecture 7b Andrew Tolmach Portland State University 1994-2017 Type Inference Some statically typed languages, like ML (and to a lesser extent Scala), offer alternative

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

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

An introduction to functional programming. July 23, 2010

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

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

Quiz 3; Tuesday, January 27; 5 minutes; 5 points [Solutions follow on next page]

Quiz 3; Tuesday, January 27; 5 minutes; 5 points [Solutions follow on next page] Quiz 3; Tuesday, January 27; 5 minutes; 5 points [Solutions follow on next page] 1. Does the Java expression x + y == z have a side-effect? If so, what is it? 2. Write a function named add that can add

More information

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

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

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

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

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

Advanced Topics in Programming Languages Lecture 2 - Introduction to Haskell

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

More information

Haskell Overloading (1) LiU-FP2016: Lecture 8 Type Classes. Haskell Overloading (3) Haskell Overloading (2)

Haskell Overloading (1) LiU-FP2016: Lecture 8 Type Classes. Haskell Overloading (3) Haskell Overloading (2) Haskell Overloading (1) LiU-FP2016: Lecture 8 Type Classes Henrik Nilsson University of Nottingham, UK What is the type of (==)? E.g. the following both work: 1 == 2 a == b I.e., (==) can be used to compare

More information

CIS 194: Homework 6. Due Friday, October 17, Preface. Setup. Generics. No template file is provided for this homework.

CIS 194: Homework 6. Due Friday, October 17, Preface. Setup. Generics. No template file is provided for this homework. CIS 194: Homework 6 Due Friday, October 17, 2014 No template file is provided for this homework. Download the markets.json file from the website, and make your HW06.hs Haskell file with your name, any

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

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

CMSC 330: Organization of Programming Languages. Functional Programming with Lists CMSC 330: Organization of Programming Languages Functional Programming with Lists 1 Lists in OCaml The basic data structure in OCaml Lists can be of arbitrary length Implemented as a linked data structure

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

CS152: Programming Languages. Lecture 11 STLC Extensions and Related Topics. Dan Grossman Spring 2011

CS152: Programming Languages. Lecture 11 STLC Extensions and Related Topics. Dan Grossman Spring 2011 CS152: Programming Languages Lecture 11 STLC Extensions and Related Topics Dan Grossman Spring 2011 Review e ::= λx. e x e e c v ::= λx. e c τ ::= int τ τ Γ ::= Γ, x : τ (λx. e) v e[v/x] e 1 e 1 e 1 e

More information

Monad Background (3A) Young Won Lim 11/8/17

Monad Background (3A) Young Won Lim 11/8/17 Copyright (c) 2016-2017 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

Type families and data kinds

Type families and data kinds Type families and data kinds AFP Summer School Wouter Swierstra 1 Today How do GADTs work? Kinds beyond * Programming with types 2 Calling functions on vectors Given two vectors xs : Vec a n and ys : Vec

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

CSE 341 Section 7. Ethan Shea Autumn Adapted from slides by Nicholas Shahan, Dan Grossman, Tam Dang, and Eric Mullen

CSE 341 Section 7. Ethan Shea Autumn Adapted from slides by Nicholas Shahan, Dan Grossman, Tam Dang, and Eric Mullen CSE 341 Section 7 Ethan Shea Autumn 2018 Adapted from slides by Nicholas Shahan, Dan Grossman, Tam Dang, and Eric Mullen Outline Interpreting MUPL Assume Correct Syntax Check for Correct Semantics Evaluating

More information

Lecture 19: Functions, Types and Data Structures in Haskell

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

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

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

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

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

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

More information

Monad Background (3A) Young Won Lim 11/18/17

Monad Background (3A) Young Won Lim 11/18/17 Copyright (c) 2016-2017 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

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

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

More information

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

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

More information

Types and Type Inference

Types and Type Inference Types and Type Inference Mooly Sagiv Slides by Kathleen Fisher and John Mitchell Reading: Concepts in Programming Languages, Revised Chapter 6 - handout on the course homepage Outline General discussion

More information

CIS 194: Homework 5. Due Monday, 18 February. Expressions. (2 + 3) 4 would be represented by the value

CIS 194: Homework 5. Due Monday, 18 February. Expressions. (2 + 3) 4 would be represented by the value CIS 194: Homework 5 Due Monday, 18 February Files you should submit: Calc.hs, containing a module of the same name. As we saw in class, Haskell s type classes provide ad-hoc polymorphism, that is, the

More information

UNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division. P. N. Hilfinger

UNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division. P. N. Hilfinger UNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division CS 164 Spring 2005 P. N. Hilfinger Project #2: Static Analyzer for Pyth Due: Wednesday, 6 April

More information

301AA - Advanced Programming [AP-2017]

301AA - Advanced Programming [AP-2017] 301AA - Advanced Programming [AP-2017] Lecturer: Andrea Corradini andrea@di.unipi.it Tutor: Lillo GalleBa galleba@di.unipi.it Department of Computer Science, Pisa Academic Year 2017/18 AP-2017-19: Type

More information

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

More information

CSc 372 Comparative Programming Languages

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

More information

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

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,

More information

CMSC 330: Organization of Programming Languages

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

More information

CIS 194: Homework 3. Due Wednesday, February 11, Interpreters. Meet SImPL

CIS 194: Homework 3. Due Wednesday, February 11, Interpreters. Meet SImPL CIS 194: Homework 3 Due Wednesday, February 11, 2015 Interpreters An interpreter is a program that takes another program as an input and evaluates it. Many modern languages such as Java 1, Javascript,

More information

Haskell Overview III (3A) Young Won Lim 10/4/16

Haskell Overview III (3A) Young Won Lim 10/4/16 (3A) 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

Principles of Programming Languages

Principles of Programming Languages Principles of Programming Languages h"p://www.di.unipi.it/~andrea/dida2ca/plp-16/ Prof. Andrea Corradini Department of Computer Science, Pisa Lesson 24! Type inference in ML / Haskell 1 Type Checking vs

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

CSE399: Advanced Programming. Handout 2

CSE399: Advanced Programming. Handout 2 CSE399: Advanced Programming Handout 2 Higher-Order Programming Functions as Data In Haskell (and other functional languages), functions can be treated as ordinary data they can be passed as arguments

More information

Background Type Classes (1B) Young Won Lim 6/28/18

Background Type Classes (1B) Young Won Lim 6/28/18 Background Type Classes (1B) Copyright (c) 2016-2017 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

More information

GADTs. Wouter Swierstra. Advanced functional programming - Lecture 7. Faculty of Science Information and Computing Sciences

GADTs. Wouter Swierstra. Advanced functional programming - Lecture 7. Faculty of Science Information and Computing Sciences GADTs Advanced functional programming - Lecture 7 Wouter Swierstra 1 Today s lecture Generalized algebraic data types (GADTs) 2 A datatype data Tree a = Leaf Node (Tree a) a (Tree a) This definition introduces:

More information

Topics Covered Thus Far CMSC 330: Organization of Programming Languages

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

More information

Advances in Programming Languages

Advances in Programming Languages T O Y H Advances in Programming Languages APL8: Multiparameter Type Classes, Constructor Classes Ian Stark School of Informatics The University of Edinburgh Thursday 4 February Semester 2 Week 4 E H U

More information

The Typed Racket Guide

The Typed Racket Guide The Typed Racket Guide Version 5.3.6 Sam Tobin-Hochstadt and Vincent St-Amour August 9, 2013 Typed Racket is a family of languages, each of which enforce

More information

Types and Type Inference

Types and Type Inference CS 242 2012 Types and Type Inference Notes modified from John Mitchell and Kathleen Fisher Reading: Concepts in Programming Languages, Revised Chapter 6 - handout on Web!! Outline General discussion of

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

Type Systems, Type Inference, and Polymorphism

Type Systems, Type Inference, and Polymorphism 6 Type Systems, Type Inference, and Polymorphism Programming involves a wide range of computational constructs, such as data structures, functions, objects, communication channels, and threads of control.

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

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

+ Abstract Data Types

+ Abstract Data Types Linked Lists Abstract Data Types An Abstract Data Type (ADT) is: a set of values a set of operations Sounds familiar, right? I gave a similar definition for a data structure. Abstract Data Types Abstract

More information

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

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

More information

Lists. Michael P. Fourman. February 2, 2010

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

More information

These notes are intended exclusively for the personal usage of the students of CS352 at Cal Poly Pomona. Any other usage is prohibited without

These notes are intended exclusively for the personal usage of the students of CS352 at Cal Poly Pomona. Any other usage is prohibited without These notes are intended exclusively for the personal usage of the students of CS352 at Cal Poly Pomona. Any other usage is prohibited without previous written authorization. 1 2 The simplest way to create

More information

Intro. Scheme Basics. scm> 5 5. scm>

Intro. Scheme Basics. scm> 5 5. scm> Intro Let s take some time to talk about LISP. It stands for LISt Processing a way of coding using only lists! It sounds pretty radical, and it is. There are lots of cool things to know about LISP; if

More information

Advanced features of Functional Programming (Haskell)

Advanced features of Functional Programming (Haskell) Advanced features of Functional Programming (Haskell) Polymorphism and overloading January 10, 2017 Monomorphic and polymorphic types A (data) type specifies a set of values. Examples: Bool: the type of

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

CMSC 330: Organization of Programming Languages

CMSC 330: Organization of Programming Languages CMSC 330: Organization of Programming Languages CMSC330 Fall 2017 OCaml Data Types CMSC330 Fall 2017 1 OCaml Data So far, we ve seen the following kinds of data Basic types (int, float, char, string) Lists

More information

Background Type Classes (1B) Young Won Lim 6/14/18

Background Type Classes (1B) Young Won Lim 6/14/18 Background Type Classes (1B) Copyright (c) 2016-2017 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

More information

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

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

More information

Informatics 1 Functional Programming Lectures 13 and 14 Monday 11 and Tuesday 12 November Type Classes. Don Sannella University of Edinburgh

Informatics 1 Functional Programming Lectures 13 and 14 Monday 11 and Tuesday 12 November Type Classes. Don Sannella University of Edinburgh Informatics 1 Functional Programming Lectures 13 and 14 Monday 11 and Tuesday 12 November 2013 Type Classes Don Sannella University of Edinburgh Mock exam Slots and rooms have now been assigned Mon 18

More information