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

Size: px
Start display at page:

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

Transcription

1 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! Fall 18 CSCI 4430, A Milanova 1 Today s Lecture Outline n Haskell: a functional programming language n Key ideas n Rich syntax (syntactic sugar), rich libraries (modules) n Lazy evaluation n Static typing and polymorphic type inference n Algebraic data types and pattern matching n Type classes n Monads and more Fall 18 CSCI 4430, A Milanova 3 Haskell Resources n n Try tutorial on front page to get started! n spring13/ n Stack Overflow! n Getting started: tutorial + slides Fall 18 CSCI 4430, A Milanova 4 Getting Started n Download the Glasgow Haskell Compiler: n n Run Haskell in interactive mode: n ghci n Type functions in a file (e.g., fun.hs), then load the file and call functions interactively Prelude > :l fun.hs [1 of 1] Compiling Main ( fun.hs, interpreted ) Ok, one module loaded. *Main > square 25 5 Getting Started: Infix Syntax n You can use prefix syntax, like in Scheme: > ((+) 1 2) --- or (+) (+) interprets + to function value > (quot 5 2) --- or quot n Or you can use infix syntax: > > 5 `quot` function value to infix operator 6 1

2 Getting Started: Lists n Lists are important in Haskell too! > [1,2] [1,2] Syntactic sugar: > ana == [ a, n, a ] --- also, [ a, n, a ] == a : [ n... True --- strings are of type [Char], Char lists > map ((+) 1) [1,2] [2,3] n Caveat: in Haskell, all elements of a list must be of same type! You can t have [[1,2],2]! 7 Getting Started: Lists n map, foldl, foldr, filter and more are built-in! > foldl (+) 0 [1,2,3] 6 > foldr (-) 0 [1,2,3] 2 > filter ((<) 0) [-1,2,0,5] [2,5] Note: different order of arguments from ones we defined in Scheme. foldl : (b * a à b) * b * [a] à b In Haskell, functions are curried: foldl:: (b à a à b) à b à [a] à b à is right associative: a à b à c is a à (b à c) 8 Getting Started: Functions n Function definition: > square x = x*x --- name params = body n Evaluation: > square 5 25 n Anonymous functions: > map (\x->x+1) [1,2,3] --- \x-> is λx. [2,3,4] Fall 18 CSCI 4430, A Milanova 9 Getting Started: Functions n Function definition: > square x = x*x --- name params = body n Just as in Scheme, you can define a function using the lambda construct: > square = \x->x*x > square 5 Fall 18 CSCI 4430, A Milanova 10 Getting Started: Higher-order Functions n Of course, higher-order functions are everywhere! --- defining apply_n in ghci: > apply_n f n x = if n==0 then x else apply_n f (n-1) (f x) --- applies f n times on x: e.g., f (f (f (f x) > apply_n ((+) 1) > fun a b = apply_n ((+) 1) a b Fall 18 CSCI 4430, A Milanova 11 Getting Started: Let Bindings n let in Haskell is same as letrec in Scheme: > let square x = x*x in square 5 25 > let lis = [ a, n, a ] in head lis a > let lis = [ a, n, a ] in tail lis na Fall 18 CSCI 4430, A Milanova 12 2

3 Getting Started: Indentation n Haskell supports ; and { } to delineate blocks n Haskell supports indentation too! iseven n = let Define function in file. Can t use indentation syntax in ghci! even n = if n == 0 then True else odd (n-1) odd n = if n == 0 then False else even (n-1) in even n > iseven Interpreters for the Lambda Calculus (for HW9) n An interpreter for the lambda calculus is a program that reduces lambda expressions to answers n We must specify n Definition of answer. Which normal form? n Reduction strategy. How do we chose redexes in an expression? Fall 18 CSCI 4430, A Milanova 14 An Interpreter (HW9) Haskell syntax: let. in case f of à Another Interpreter (HW9) n Definition by cases on E ::= x λx. E 1 E 1 E 2 interpret(x) = x Apply the function interpret(λx.e 1 ) = λx.e before interpreting the 1 argument interpret(e 1 E 2 ) = let f = interpret(e 1 ) in case f of λx.e 3 à interpret(e 3 [E 2 /x]) - à f E 2 n What normal form: Weak head normal form n What strategy: Normal order Fall 18 CSCI 4430, A Milanova (modified from MIT 2015 Program Analysis OCW) 15 n Definition by cases on E ::= x λx. E 1 E 1 E 2 interpret(x) = x interpret(λx.e 1 ) = λx.e 1 interpret(e 1 E 2 ) = let f = interpret(e 1 ) a = interpret(e 2 ) in case f of λx.e 3 à interpret(e 3 [a/x]) - à f a n What normal form: Weak head normal form n What strategy: Applicative order 16 n In HW9 An Interpreter (HW9) n First, you will write the pseudocode for an interpreter that n Reduces to answers in Normal Form n n Uses applicative order reduction Then, you ll code this interpreter in Haskell Fall 18 CSCI 4430, A Milanova 17 Lecture Outline n Haskell: a functional programming language n Key ideas n Rich syntax, rich libraries (modules) n Lazy evaluation n Static typing and polymorphic type inference n Algebraic data types and pattern matching n Type classes n Monads and more Fall 18 CSCI 4430, A Milanova 18 3

4 Lazy Evaluation n Unlike Scheme (and most programming languages) Haskell does lazy evaluation, i.e., normal order reduction n It won t evaluate an expression until it is needed > f x = [] --- f takes x and returns the empty list > f (repeat 1) --- repeat produces infinite list [1,1 > [] > head ([1..]) --- [1..] is the infinite list of integers > 1 n Lazy evaluation allows work with infinite structures! 19 Lazy Evaluation > f x = x*x > f (5+1) --- evaluates to (5+1) * (5+1) --- evaluates argument only when needed > fun n = n : fun(n+1) > head (fun 5) : denotes cons : constructs a list with head n and tail fun(n-1) n Exercise: write a function that returns the (infinite) list of prime numbers 20 Static Typing and Type Inference n Unlike Scheme, which is dynamically typed, Haskell is statically typed! n Unlike Java/C++ we don t have to write type annotations. Haskell infers types! > let f x = head x in f True Couldn't match expected type [a] with actual type Bool In the first argument of f, namely True In the expression: f True 21 Static Typing and Type Inference n Recall apply_n f n x: > apply_n f n x = if n==0 then x else apply_n f (n-1) (f x) > apply_n ((+) 1) True 0 <interactive>:32:1: error: Could not deduce (Num Bool) arising from a use of apply_n from the context: Num t2 bound by the inferred type of it :: Num t2 => t2 at <interactive>:32:1-22 In the expression: apply_n ((+) 1) True 0 In an equation for it : it = apply_n ((+) 1) True 0 22 Algebraic Data Types n Algebraic data types are tagged unions (aka sums) of products (aka records) data Shape = Line Point Point Triangle Point Point Point Quad Point Point Point Point union Algebraic Data Types n Constructors create values of the data type let l1::shape l1 = Line e1 e2 Haskell keyword the new type new constructors (a.k.a. tags, disjuncts, summands) Line is a binary constructor, Triangle is a ternary Fall 18 CSCI 4430, A Milanova (example from MIT 2015 Program Analysis OCW) 23 t1::shape = Triangle e3 e4 e5 q1::shape = Quad e6 e7 e8 e9 in Fall 18 CSCI 4430, A Milanova (example from MIT 2015 Program Analysis OCW) 24 4

5 Algebraic Data Types in HW9 n Defining a lambda expression type Name = String data Expr = Var Name Lambda Name Expr App Expr Expr > e1 = Var x // Lambda term x > e2 = Lambda x e1 // Lambda term λx.x Fall 18 CSCI 4430, A Milanova 25 Exercise: Define an ADT for Expressions in your Scheme HW6 type Name = String data Expr = Var Name Val Bool And Expr Expr Or Expr Expr Let Name Expr Expr evaluate :: Expr à [(Name,Bool)] à Bool evaluate e env = Fall 18 CSCI 4430, A Milanova 26 Examples of Algebraic Data Types data Bool = True False data Day = Mon Tue Wed Thu Fri Sat Sun data List a = Nil Cons a (List a) data Tree a = Leaf a Node (Tree a) (Tree a) data Maybe a = Nothing Just a Polymorphic types. a is a type parameter! Maybe type denotes that result of computation can be a or Nothing. Maybe is a monad. Fall 18 CSCI 4430, A Milanova (examples from MIT 2015 Program Analysis OCW) 27 Pattern Matching Type signature of anchorpnt: takes a Shape and returns a Point. n Examine values of an algebraic data type anchorpnt :: Shape -> Point anchorpnt s = case s of Line p1 p2 -> p1 Triangle p3 p4 p5 -> p3 Quad p6 p7 p8 p9 -> p6 n Two points n Test: does the given value match this pattern? n Binding: if value matches, bind corresponding values of s and pattern Fall 18 CSCI 4430, A Milanova (from MIT 2015 Program Analysis OCW) 28 Pattern Matching n Pattern matching deconstructs a term > let h:t = "ana" in t na > let (x,y) = (10, ana ) in x 10 Fall 18 CSCI 4430, A Milanova 29 Pattern Matching in HW9 isfree::name à Expr à Bool isfree v e = case e of Var n à if (n == v) then True else False Lambda Type signature of isfree. In Haskell, all functions are curried, i.e., they take just one argument. isfree takes a variable name, and returns a function that takes an expression and returns a boolean. Of course, we can interpret isfree as a function that takes a variable name name and an expression E, and returns true if variable name is free in E. Fall 18 CSCI 4430, A Milanova 30 5

6 Generic Functions in Haskell n We can generalize a function when a function makes no assumptions about the type: const :: a -> b -> a const x y = x apply :: (a->b)->a->b apply g x = g x Fall 18 CSCI 4430, A Milanova (examples from MIT 2015 Program Analysis OCW) 31 Generic Functions -- List datatype data List a = Nil Cons a (List a) n Can we have sum of parameterized type? sum :: a -> List a -> a sum n Nil = n sum n (Cons x xs) = sum (n+x) xs n No. a no longer unconstraint. Type and function definition imply that + is of type a->a->a but n + is not defined for all types! 32 Haskell Type Classes n Define a type class containing the arithmetic operators class Num a where (==) :: a -> a -> Bool (+) :: a -> a -> a instance Num Int where x == y = instance Num Float where Read: A type a is an instance of the type class Num if it provides overloaded definitions of operations ==, +, Read: Int and Float are instances of Num Generic Functions with Type Class sum :: (Num a) => a -> List a -> a sum n Nil = n sum n (Cons x xs) = sum (n+x) xs n One view of type classes: predicates n (Num a) is a predicate in type definitions n Constrains the types we can instantiate a generic function to specific types n A type class has associated laws Fall 18 CSCI 4430, A Milanova 33 Fall 18 CSCI 4430, A Milanova 34 Type Class Hierarchy Lecture Outline class Eq a where (==), (/=) :: a -> a -> Bool n Haskell: a functional programming language class (Eq a) => Ord where (<), (<=), (>), (>=) :: a -> a -> Bool min, max :: a -> a -> a n Each type class corresponds to one concept n Class constraints give rise to a hierarchy n Eq is a superclass of Ord n Ord inherits specification of (==) and (/=) n Notion of true subtyping Fall 18 CSCI 4430, A Milanova (modified from MIT 2015 Program Analysis OCW) 35 n Key ideas n Rich syntax, rich libraries (modules) n Lazy evaluation n Static typing and polymorphic type inference n Algebraic data types and pattern matching n Type classes n Monads and more Fall 18 CSCI 4430, A Milanova 36 6

7 Monads n A way to cleanly compose computations n E.g., f may return a value of type a or Nothing Composing computations becomes tedious: case (f s) of Nothing à Nothing Just m à case (f m) n In Haskell, monads encapsulate IO and other imperative features Fall 18 CSCI 4430, A Milanova 37 An Example: Cloned Sheep type Sheep = father :: Sheep à Maybe Sheep father =... mother :: Sheep à Maybe Sheep mother = (Note: a cloned sheep may have both parents, or not...) maternalgrandfather :: Sheep à Maybe Sheep maternalgrandfather s = case (mother s) of Nothing à Nothing Just m à father m Fall 18 CSCI 4430, A Milanova (Example from All About Monads Tutorial) 38 An Example The Monad Type Class motherspaternalgrandfather :: Sheep à Maybe Sheep motherspaternalgrandfather s = case (mother s) of Nothing à Nothing Just m à case (father m) of Nothing à Nothing Just gf à father gf n Tedious, unreadable, difficult to maintain n Monads help! Fall 18 CSCI 4430, A Milanova (Example from All About Monads Tutorial) 39 n Haskell s Monad class requires 2 operations, >>= (bind) and return class Monad m where // >>= (the bind operation) takes a monad // m a, and a function that takes a and turns // it into a monad m b (>>=) :: m a à (a à m b) à m b // return encapsulates a value into the monad return :: a à m a 40 The Maybe Monad The List Monad instance Monad Maybe where Nothing >>= f = Nothing (Just x) >>= f = f x return = Just n Cloned Sheep example: motherspaternalgrandfather s = (return s) >>= mother >>= father >>= father (Note: if at any point, some function returns Nothing, Nothing gets cleanly propagated.) 41 n The List type constructor is a monad li >>= f = concat (map f li) return x = [x] Note: concat::[[a]] à [a] e.g., concat [[1,2],[3,4],[5,6]] yields [1,2,3,4,5,6] n Use any f s.t. f::aà[b]. f may yield a list of 0,1,2, elements of type b, e.g., > f x = [x+1] > [1,2,3] >>= f --- yields [2,3,4] 42 7

8 The List Monad parents :: Sheep à [Sheep] parents s = MaybeToList (mother s) ++ MaybeToList (father s) grandparents :: Sheep à [Sheep] grandparents s = (parents s) >>= parents The do Notation (Syntactic Sugar!) > f x = x+1 > g x = x*5 > [1,2,3] >>= (return. f) >>= (return. g) Or > [1,2,3] >>= (return. \x->x+1) >>= (return. \y->y*5) Or > do { x <- [1,2,3]; y <- (return. f) x; (return. g) y } Fall 18 CSCI 4430, A Milanova List Comprehensions > [ x x <- [1,2,3,4] ] [1,2,3,4] > [ x x <- [1,2,3,4], x `mod` 2 == 0 ] [2,4] > [ [x,y] x <- [1,2,3], y <- [6,5,4] ] [[1,6],[1,5],[1,4],[2,6],[2,5],[2,4],[3,6],[3,5],[3,4]] --- Willy s all-pairs function from test Fall 18 CSCI 4430, A Milanova 45 List Comprehensions n List comprehensions are syntactic sugar [ x x <- [1,2,3,4] ] is syntactic sugar for do { x <- [1,2,3,4]; return x } [ [x,y] x <- [1,2,3], y <- [6,5,4] ] synt. sugar for do { x <- [1,2,3]; y<-[6,5,4]; return [x,y] } Fall 18 CSCI 4430, A Milanova 46 Monads n A way to cleanly compose (build) computations n A way to encapsulate IO and other imperative features Fall 18 CSCI 4430, A Milanova 47 Spring 18 CSCI 4450/6450, A Milanova 48 8

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

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

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

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

What does my program mean?

What does my program mean? September 16, 2015 L02-1 What does my program mean? Armando Solar Lezama Computer Science and Artificial Intelligence Laboratory M.I.T. Adapted from Arvind 2010. Used with permission. September 16, 2015

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

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

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

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

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

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

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

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

n n Official Scala website n Scala API n

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

More information

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

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

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

n Closed book n You are allowed 5 cheat pages n Practice problems available in Course Materials n Check grades in Rainbow grades

n Closed book n You are allowed 5 cheat pages n Practice problems available in Course Materials n Check grades in Rainbow grades Announcements Announcements n HW12: Transaction server n Due today at 2pm n You can use up to 2 late days, as always n Final Exam, December 17, 3-6pm, in DCC 308 and 318 n Closed book n You are allowed

More information

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

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

More information

COSE212: Programming Languages. Lecture 3 Functional Programming in OCaml

COSE212: Programming Languages. Lecture 3 Functional Programming in OCaml COSE212: Programming Languages Lecture 3 Functional Programming in OCaml Hakjoo Oh 2017 Fall Hakjoo Oh COSE212 2017 Fall, Lecture 3 September 18, 2017 1 / 44 Why learn ML? Learning ML is a good way of

More information

CS 11 Haskell track: lecture 4. n This week: Monads!

CS 11 Haskell track: lecture 4. n This week: Monads! CS 11 Haskell track: lecture 4 This week: Monads! Monads Have already seen an example of a monad IO monad But similar concepts can be used for a lot of completely unrelated tasks Monads are useful "general

More information

Lazy Functional Programming in Haskell

Lazy Functional Programming in Haskell Lazy Functional Programming in Haskell David Raymond Christiansen 25 November, 2013 What is Haskell? 2 What is Haskell? Pure functional language: no side effects 2 What is Haskell? Pure functional language:

More information

CSCE 314 Programming Languages

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

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

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

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

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

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

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

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

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

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

COP4020 Programming Languages. Functional Programming Prof. Robert van Engelen

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

More information

CS 457/557: Functional Languages

CS 457/557: Functional Languages CS 457/557: Functional Languages From Trees to Type Classes Mark P Jones Portland State University 1 Trees:! " There are many kinds of tree data structure.! " For example: data BinTree a = Leaf a BinTree

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

Typed Racket: Racket with Static Types

Typed Racket: Racket with Static Types Typed Racket: Racket with Static Types Version 5.0.2 Sam Tobin-Hochstadt November 6, 2010 Typed Racket is a family of languages, each of which enforce that programs written in the language obey a type

More information

Programming in Haskell Aug-Nov 2015

Programming in Haskell Aug-Nov 2015 Programming in Haskell Aug-Nov 2015 LECTURE 14 OCTOBER 1, 2015 S P SURESH CHENNAI MATHEMATICAL INSTITUTE Enumerated data types The data keyword is used to define new types data Bool = False True data Day

More information

Programming Paradigms

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

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

Principles of Programming Languages

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

More information

Overview. Declarative Languages D7012E. Overloading. Overloading Polymorphism Subtyping

Overview. Declarative Languages D7012E. Overloading. Overloading Polymorphism Subtyping Overview Declarative Languages D7012E Lecture 4: The Haskell type system Fredrik Bengtsson / Johan Nordlander Overloading & polymorphism Type classes instances of type classes derived type classes Type

More information

Logic - CM0845 Introduction to Haskell

Logic - CM0845 Introduction to Haskell Logic - CM0845 Introduction to Haskell Diego Alejandro Montoya-Zapata EAFIT University Semester 2016-1 Diego Alejandro Montoya-Zapata (EAFIT University) Logic - CM0845 Introduction to Haskell Semester

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

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

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

INTRODUCTION TO FUNCTIONAL PROGRAMMING

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

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

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

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

Lecture 5: Lazy Evaluation and Infinite Data Structures

Lecture 5: Lazy Evaluation and Infinite Data Structures Lecture 5: Lazy Evaluation and Infinite Data Structures Søren Haagerup Department of Mathematics and Computer Science University of Southern Denmark, Odense October 3, 2017 How does Haskell evaluate a

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

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

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-16: Haskell,

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

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

A Third Look At ML. Chapter Nine Modern Programming Languages, 2nd ed. 1

A Third Look At ML. Chapter Nine Modern Programming Languages, 2nd ed. 1 A Third Look At ML Chapter Nine Modern Programming Languages, 2nd ed. 1 Outline More pattern matching Function values and anonymous functions Higher-order functions and currying Predefined higher-order

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

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

(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

Programming Languages Lecture 14: Sum, Product, Recursive Types

Programming Languages Lecture 14: Sum, Product, Recursive Types CSE 230: Winter 200 Principles of Programming Languages Lecture 4: Sum, Product, Recursive Types The end is nigh HW 3 No HW 4 (= Final) Project (Meeting + Talk) Ranjit Jhala UC San Diego Recap Goal: Relate

More information

CPS 506 Comparative Programming Languages. Programming Language Paradigm

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

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

Organization of Programming Languages CS3200/5200N. Lecture 11

Organization of Programming Languages CS3200/5200N. Lecture 11 Organization of Programming Languages CS3200/5200N Razvan C. Bunescu School of Electrical Engineering and Computer Science bunescu@ohio.edu Functional vs. Imperative The design of the imperative languages

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

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

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

Data Types The ML Type System

Data Types The ML Type System 7 Data Types 7.2.4 The ML Type System The following is an ML version of the tail-recursive Fibonacci function introduced Fibonacci function in ML in Section 6.6.1: EXAMPLE 7.96 1. fun fib (n) = 2. let

More information

Programming Paradigms

Programming Paradigms PP 2017/18 Unit 12 Functions and Data Types in Haskell 1/45 Programming Paradigms Unit 12 Functions and Data Types in Haskell J. Gamper Free University of Bozen-Bolzano Faculty of Computer Science IDSE

More information

Chapter 15. Functional Programming Languages

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

More information

Typed Scheme: Scheme with Static Types

Typed Scheme: Scheme with Static Types Typed Scheme: Scheme with Static Types Version 4.1.1 Sam Tobin-Hochstadt October 5, 2008 Typed Scheme is a Scheme-like language, with a type system that supports common Scheme programming idioms. Explicit

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

Functional Logic Programming Language Curry

Functional Logic Programming Language Curry Functional Logic Programming Language Curry Xiang Yin Department of Computer Science McMaster University November 9, 2010 Outline Functional Logic Programming Language 1 Functional Logic Programming Language

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

IA014: Advanced Functional Programming

IA014: Advanced Functional Programming IA014: Advanced Functional Programming 8. GADT Generalized Algebraic Data Types (and type extensions) Jan Obdržálek obdrzalek@fi.muni.cz Faculty of Informatics, Masaryk University, Brno Motivation IA014

More information

Lecture 8: Summary of Haskell course + Type Level Programming

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

More information

Introduction to OCaml

Introduction to OCaml Fall 2018 Introduction to OCaml Yu Zhang Course web site: http://staff.ustc.edu.cn/~yuzhang/tpl References Learn X in Y Minutes Ocaml Real World OCaml Cornell CS 3110 Spring 2018 Data Structures and Functional

More information

Exercise 1 ( = 24 points)

Exercise 1 ( = 24 points) 1 Exercise 1 (4 + 5 + 4 + 6 + 5 = 24 points) The following data structure represents polymorphic binary trees that contain values only in special Value nodes that have a single successor: data Tree a =

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

Monad (1A) Young Won Lim 6/26/17

Monad (1A) Young Won Lim 6/26/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 system. Type theory. Haskell type system. EDAN40: Functional Programming Types and Type Classes (revisited)

Type system. Type theory. Haskell type system. EDAN40: Functional Programming Types and Type Classes (revisited) Type system EDAN40: Functional Programming Types and Type Classes (revisited) Jacek Malec Dept. of Computer Science, Lund University, Sweden April 3rd, 2017 In programming languages, a type system is a

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

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

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

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

Haskell Scripts. Yan Huang

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

More information

CS 320 Midterm Exam. Fall 2018

CS 320 Midterm Exam. Fall 2018 Name: BU ID: CS 320 Midterm Exam Fall 2018 Write here the number of the problem you are skipping: You must complete 5 of the 6 problems on this exam for full credit. Each problem is of equal weight. Please

More information

Introduction to ML. Mooly Sagiv. Cornell CS 3110 Data Structures and Functional Programming

Introduction to ML. Mooly Sagiv. Cornell CS 3110 Data Structures and Functional Programming Introduction to ML Mooly Sagiv Cornell CS 3110 Data Structures and Functional Programming Typed Lambda Calculus Chapter 9 Benjamin Pierce Types and Programming Languages Call-by-value Operational Semantics

More information

Algebraic Types. Chapter 14 of Thompson

Algebraic Types. Chapter 14 of Thompson Algebraic Types Chapter 14 of Thompson Types so far Base types Int, Integer, Float, Bool, Char Composite types: tuples (t 1,t 2,,t n ) lists [t 1 ] functions (t 1 -> t 2 ) Algebraic types enumerated, product

More information

Haskell & functional programming, some slightly more advanced stuff. Matteo Pradella

Haskell & functional programming, some slightly more advanced stuff. Matteo Pradella Haskell & functional programming, some slightly more advanced stuff Matteo Pradella pradella@elet.polimi.it IEIIT, Consiglio Nazionale delle Ricerche & DEI, Politecnico di Milano PhD course @ UniMi - Feb

More information

Recursion and Induction: Haskell; Primitive Data Types; Writing Function Definitions

Recursion and Induction: Haskell; Primitive Data Types; Writing Function Definitions Recursion and Induction: Haskell; Primitive Data Types; Writing Function Definitions Greg Plaxton Theory in Programming Practice, Spring 2005 Department of Computer Science University of Texas at Austin

More information

CSCI-GA Final Exam

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

More information

Monad (1A) Young Won Lim 6/21/17

Monad (1A) Young Won Lim 6/21/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

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

Advanced Programming Handout 7. Monads and Friends (SOE Chapter 18)

Advanced Programming Handout 7. Monads and Friends (SOE Chapter 18) Advanced Programming Handout 7 Monads and Friends (SOE Chapter 18) The Type of a Type In previous chapters we discussed: Monomorphic types such as Int, Bool, etc. Polymorphic types such as [a], Tree a,

More information

Introduction to ML. Mooly Sagiv. Cornell CS 3110 Data Structures and Functional Programming

Introduction to ML. Mooly Sagiv. Cornell CS 3110 Data Structures and Functional Programming Introduction to ML Mooly Sagiv Cornell CS 3110 Data Structures and Functional Programming The ML Programming Language General purpose programming language designed by Robin Milner in 1970 Meta Language

More information

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

The type checker will complain that the two branches have different types, one is string and the other is int 1 Intro to ML 1.1 Basic types Need ; after expression - 42 = ; val it = 42 : int - 7+1; val it = 8 : int Can reference it - it+2; val it = 10 : int - if it > 100 then "big" else "small"; val it = "small"

More information

Applicative, traversable, foldable

Applicative, traversable, foldable Applicative, traversable, foldable Advanced functional programming - Lecture 3 Wouter Swierstra 1 Beyond the monad So far, we have seen how monads define a common abstraction over many programming patterns.

More information

Lecture #23: Conversion and Type Inference

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

More information