Principles of Programming Languages, 3

Size: px
Start display at page:

Download "Principles of Programming Languages, 3"

Transcription

1 Principles of Programming Languages, 3 Matteo Pradella May 2015 Matteo Pradella Principles of Programming Languages, 3 May / 94

2 1 Introduction on purity and evaluation 2 Haskell Matteo Pradella Principles of Programming Languages, 3 May / 94

3 A bridge toward Haskell 1 We will consider now some basic concepts of Haskell, by implementing them in Scheme: 2 What is a pure functional language? 3 Non-strict evaluation strategies 4 Currying Matteo Pradella Principles of Programming Languages, 3 May / 94

4 What is a functional language? 1 In mathematics, functions do not have side-effects 2 e.g. if f : N N, f (5) is a fixed value in N, and do not depend on time (also called referential transparency) 3 this is clearly not true in conventional programming languages, Scheme included 4 Scheme is mainly functional, as programs are expressions, and computation is evaluation of such expressions 5 but some expressions have side-effects, e.g. vector-set! 6 Haskell is pure, so we will see later how to manage inherently side-effectful computations (e.g. those with I/O) Matteo Pradella Principles of Programming Languages, 3 May / 94

5 Evaluation of functions 1 We have already seen that, in absence of side effects (purely functional computations) from the point of view of the result the order in which functions are applied does not matter (almost). 2 However, it matters in other aspects, consider e.g. this function: ( define ( sum- square x y) (+ (* x x) (* y y ))) Matteo Pradella Principles of Programming Languages, 3 May / 94

6 Evaluation of functions (Scheme) 1 A possible evaluation: ( sum- square (+ 1 2) (+ 2 3)) ;; applying the first + = ( sum- square 3 (+ 2 3)) ;; applying + = ( sum- square 3 5) ;; applying sum- square = (+ (* 3 3)(* 5 5))... = 34 2 is it that of Scheme? Matteo Pradella Principles of Programming Languages, 3 May / 94

7 Evaluation of functions (alio modo) ( sum- square (+ 1 2) (+ 2 3)) ;; applying sum- square = (+ (* (+ 1 2)(+ 1 2))(* (+ 2 3)(+ 2 3))) ;; evaluating the first (+ 1 2) = (+ (* 3 (+ 1 2))(* (+ 2 3)(+ 2 3)))... = (+ (* 3 3)(* 5 5))... = 34 1 The two evaluations differ in the order in which function applications are evaluated. 2 A function application ready to be performed is called a reducible expression (or redex) Matteo Pradella Principles of Programming Languages, 3 May / 94

8 Evaluation strategies: call-by-value 1 in the first example of evaluation of mult, redexes are evaluated according to a (leftmost) innermost strategy 2 i.e., when there is more than one redex, the leftmost one that does not contain other redexes is evaluated 3 e.g. in (sum-square (+ 1 2) (+ 2 3)) there are 3 redexes: (sum-square (+ 1 2) (+ 2 3))), (+ 1 2) and (+ 2 3) the innermost that is also leftmost is (+ 1 2), which is applied, giving expression (sum-square 3 (+ 2 3)) 4 in this strategy, arguments of functions are always evaluated before evaluating the function itself - this corresponds to passing arguments by value. 5 note that Scheme does not require that we take the leftmost, but this is very common in mainstream languages Matteo Pradella Principles of Programming Languages, 3 May / 94

9 Evaluation strategies: call-by-name 1 a dual evaluation strategy: redexes are evaluated in an outermost fashion 2 we start with the redex that is not contained in any other redex, i.e. in the example above, with (sum-square (+ 1 2) (+ 2 3)), which yields (+ (* (+ 1 2)(+ 1 2))(* (+ 2 3)(+ 2 3))) 3 in the outermost strategy, functions are always applied before their arguments, this corresponds to passing arguments by name (like in Algol 60). Matteo Pradella Principles of Programming Languages, 3 May / 94

10 Termination and call-by-name 1 e.g. first we define the following two simple functions: ( define ( infinity ) (+ 1 ( infinity ))) ( define ( fst x y) x) 2 consider the expression (fst 3 (infinity)): 1 Call-by-value: (fst 3 (infinity)) = (fst 3 (+ 1 (infinity))) = (fst 3 (+ 1 (+ 1 (infinity)))) =... 2 Call-by-name: (fst 3 (infinity)) = 3 3 if there is an evaluation for an expression that terminates, call-by-name terminates, and produces the same result (Church-Rosser confluence) Matteo Pradella Principles of Programming Languages, 3 May / 94

11 Haskell is lazy: call-by-need 1 In call-by-name, if the argument is not used, it is never evaluated; if the argument is used several times, it is re-evaluated each time 2 Call-by-need is a memoized version of call-by-name where, if the function argument is evaluated, that value is stored for subsequent uses 3 In a pure (effect-free) setting, this produces the same results as call-by-name, and it is usually faster Matteo Pradella Principles of Programming Languages, 3 May / 94

12 Call-by-need implementation: macros and thunks 1 we saw that macros are different from function, as they do not evaluate and are expanded at compile time 2 a possible idea to overcome the nontermination of (fst 3 (infinity)), could be to use thunks to prevent evaluation, and then force it with an explicit call 3 indeed, there is already an implementation in Racket based on delay and force 4 we ll see how to implement them with macros and thunks Matteo Pradella Principles of Programming Languages, 3 May / 94

13 Delay and force: call-by-name and by-need 1 Delay is used to return a promise to execute a computation (implements call-by-name) 2 moreover, it caches the result (memoization) of the computation on its first evaluation and returns that value on subsequent calls (implements call-by-need) Matteo Pradella Principles of Programming Languages, 3 May / 94

14 Promise ( struct promise ( proc ; thunk or value value? ; already evaluated? ) #: mutable ) Matteo Pradella Principles of Programming Languages, 3 May / 94

15 Delay (code) ( define- syntax delay ( syntax-rules () ((_ ( expr...)) ( promise ( lambda () ( expr...)) ; a thunk #f )))) ; still to be evaluated Matteo Pradella Principles of Programming Languages, 3 May / 94

16 Force (code) 1 force is used to force the evaluation of a promise: ( define ( force prom ) ( cond ; is it already a value? (( not ( promise? prom )) prom ) ; is it an evaluated promise? (( promise- value? prom ) ( promise- proc prom )) ( else ( set- promise- proc! prom (( promise- proc prom ))) ( set-promise-value?! prom #t) ( promise-proc prom )))) Matteo Pradella Principles of Programming Languages, 3 May / 94

17 Examples ( define x ( delay (+ 2 5))) ; a promise ( force x) ;; => 7 ( define lazy- infinity ( delay ( infinity ))) ( force ( fst 3 lazy-infinity )) ; => 3 ( fst 3 lazy- infinity ) ; = > 3 ( force ( delay ( fst 3 lazy-infinity ))) ; => 3 1 here we have call-by-need only if we make every function call a promise 2 in Haskell call-by-need is the default: if we need call-by-value, we need to force the evaluation (we ll see how) Matteo Pradella Principles of Programming Languages, 3 May / 94

18 Currying 1 in Haskell, functions have only one argument! 2 this is not a limitation, because functions with more arguments are curried 3 we see here in Scheme what it means. Consider the function: ( define ( sum- square x y) (+ (* x x) (* y y ))) 4 it has signature sum-square : C 2 C, if we consider the most general kind of numbers in Scheme, i.e. the complex field Matteo Pradella Principles of Programming Languages, 3 May / 94

19 Currying (cont.) 1 curried version: ( define ( sum-square x) ( lambda (y) (+ (* x x) (* y y )))) ;; shorter version : ( define (( sum-square x) y) (+ (* x x) (* y y ))) 2 it can be used almost as the usual version: ((sum-square 3) 5) 3 the curried version has signature sum-square : C (C C) i.e. C C C ( is right associative) Matteo Pradella Principles of Programming Languages, 3 May / 94

20 Currying in Haskell 1 in Haskell every function is automatically curried and consequently managed 2 the name currying, coined by Christopher Strachey in 1967, is a reference to logician Haskell Curry 3 the alternative name Schönfinkelisation has been proposed as a reference to Moses Schönfinkel but didn t catch on Matteo Pradella Principles of Programming Languages, 3 May / 94

21 Haskell 1 Born in 1990, designed by committee to be: 1 purely functional 2 call-by-need (sometimes called lazy evaluation) 3 strong polymorphic and static typing 2 Standards: Haskell 98 and 10 3 Motto: "Avoid success at all costs" 1 ex. usage: Google s Ganeti cluster virtual server management tool 4 I mainly follow Hudak, Peterson, Fasel, A Gentle Introduction to Haskell 98, Beware! There are many bad tutorials on Haskell and monads, in particular, available online Matteo Pradella Principles of Programming Languages, 3 May / 94

22 A taste of Haskell s syntax 1 more complex and "human" than Scheme: parentheses are optional! 2 function call is similar, though: f x y stands for f(x,y) 3 there are infix operators and are made of non-alphabetic characters (e.g. *, +, but also <++>) 4 elem is. If you want to use it infix, just use elem this is a comment 6 lambdas: (lambda (x y) (+ 1 x y)) is written \x y -> 1+x+y Matteo Pradella Principles of Programming Languages, 3 May / 94

23 Types! 1 Haskell has static typing, i.e. the type of everything must be known at compile time 2 there is type inference, so usually we do not need to explicitly declare types 3 has type is written :: instead of : (the latter is cons) 4 e.g. 1 5 :: Integer 2 a :: Char 3 inc :: Integer -> Integer 4 [1, 2, 3] :: [Integer] equivalent to 1:(2:(3:[])) 5 ( b, 4) :: (Char, Integer) 6 strings are lists of characters Matteo Pradella Principles of Programming Languages, 3 May / 94

24 Function definition 1 functions are declared through a sequence of equations 2 e.g. inc n = n + 1 length :: [ Integer ] -> Integer length [] = 0 length ( x: xs) = 1 + length xs 3 this is also an example of pattern matching 4 arguments are matched with the right parts of equations, top to bottom 5 if the match succeeds, the function body is called Matteo Pradella Principles of Programming Languages, 3 May / 94

25 Parametric Polymorphism 1 the previous definition of length could work with any kind of lists, not just those made of integers 2 indeed, if we omit its type declaration, it is inferred by Haskell as having type length :: [a] -> Integer 3 lower case letters are type variables, so [a] stands for a list of elements of type a, for any a Matteo Pradella Principles of Programming Languages, 3 May / 94

26 Main characteristics of Haskell s type system 1 every well-typed expression is guaranteed to have a unique principal type 1 it is (roughly) the least general type that contains all the instances of the expression 2 e.g. length :: a -> Integer is too general, while length :: [Integer] -> a is too specific 2 Haskell adopts a variant of the Hindley-Milner type system (used also in ML variants, e.g. F#) 3 and the principal type can be inferred automatically 4 Ref. paper: L. Cardelli, Type Systems, 1997 Matteo Pradella Principles of Programming Languages, 3 May / 94

27 User-defined types 1 are based on data declarations -- a " sum " type ( union in C) data Bool = False True 2 Bool is the (nullary) type constructor, while False and True are data constructors (nullary as well) 3 data and type constructors live in separate name-spaces, so it is possible (and common) to use the same name for both: -- a " product " type ( struct in C) data Pnt a = Pnt a a 4 if we apply a data constructor we obtain a value (e.g. Pnt ), while with a type constructor we obtain a type (e.g. Pnt Bool) Matteo Pradella Principles of Programming Languages, 3 May / 94

28 Recursive types 1 classical recursive type example: data Tree a = Leaf a Branch ( Tree a) ( Tree a) 2 e.g. data constructor Branch has type: Branch :: Tree a - > Tree a - > Tree a 3 An example tree: atree = Branch ( Leaf a ) ( Branch ( Leaf b ) ( Leaf c )) 4 in this case atree has type Tree Char Matteo Pradella Principles of Programming Languages, 3 May / 94

29 Lists are recursive types 1 Of course, also lists are recursive. Using Scheme jargon, they could be defined by: data List a = Null Cons a ( List a) 2 but Haskell has special syntax for them; in "pseudo-haskell": data [a] = [] a : [a] 3 [] is a data and type constructor, while : is an infix data constructor Matteo Pradella Principles of Programming Languages, 3 May / 94

30 An example function on Trees fringe :: Tree a -> [a] fringe ( Leaf x) = [x] fringe ( Branch left right ) = fringe left ++ fringe right 1 (++) denotes list concatenation, what is its type? Matteo Pradella Principles of Programming Languages, 3 May / 94

31 Syntax for fields 1 as we saw, product types (e.g. data Point = Point Float Float) are like struct in C or in Scheme (analogously, sum types are like union) 2 the access is positional, for instance we may define accessors: pointx Point x _ = x pointy Point _ y = y 3 there is a C-like syntax to have named fields: data Point = Point {pointx, pointy :: Float} 4 this declaration automatically defines two field names pointx, pointy 5 and their corresponding selector functions Matteo Pradella Principles of Programming Languages, 3 May / 94

32 Type synonyms 1 are defined with the keyword type 2 some examples type String = [ Char ] type Assoc a b = [(a,b)] 3 usually for readability or shortness Matteo Pradella Principles of Programming Languages, 3 May / 94

33 Newtype 1 newtype is used when we want to define a type with the same representation and behavior of an existing type (like type) 2 but having a separate identity in the type system (e.g. we want to define a kind of string [Char]) 3 e.g. newtype Str = Str [Char] 4 note: we need to define a data constructor, to distinguish it from String 5 its data constructor is not lazy (difference with data) Matteo Pradella Principles of Programming Languages, 3 May / 94

34 More on functions and currying 1 Haskell has map, and it can be defined as: map f [] = [] map f (x:xs) = f x : map f xs 2 we can partially apply also infix operators, by using parentheses: (+ 1) or (1 +) or (+) map (1 +) [1,2,3] -- => [2,3,4] Matteo Pradella Principles of Programming Languages, 3 May / 94

35 REPL 1 :t at the prompt is used for getting type, e.g. Prelude > :t (+1) (+1) :: Num a => a -> a Prelude > : t + < interactive >: 1: 1: parse error on input + Prelude > : t (+) (+) :: Num a => a -> a -> a 2 Prelude is the standard library 3 we ll see later the exact meaning of Num a => with type classes. Its meaning here is that a must be a numerical type Matteo Pradella Principles of Programming Languages, 3 May / 94

36 Function composition and $ 1 (.) is used for composing functions (i.e. (f.g)(x) is f(g(x))) Prelude > let dd = (*2). (1+) Prelude > dd 6 14 Prelude > :t (.) (.) :: (b -> c) -> (a -> b) -> a -> c 2 $ syntax for avoiding parentheses, e.g. (10*) (5+3) = (10*) $ 5+3 Matteo Pradella Principles of Programming Languages, 3 May / 94

37 Infinite computations 1 call-by-need is very convenient for dealing with never-ending computations that provide data 2 here are some simple example functions: ones = 1 : ones numsfrom n = n : numsfrom ( n +1) squares = map ( ^2) ( numsfrom 0) 3 clearly, we cannot evaluate them (why?), but there is take to get finite slices from them 4 e.g. take 5 squares = [0,1,4,9,16] Matteo Pradella Principles of Programming Languages, 3 May / 94

38 Infinite lists 1 Convenient syntax for creating infinite lists: 2 e.g. ones before can be also written as [1,1..] 3 numsfrom 6 is the same as [6..] 4 zip is a useful function having type zip :: [a] -> [b] -> [(a, b)] zip [1,2,3] " ciao " -- => [(1, c ),(2, i ),(3, a )] 5 list comprehensions [(x,y) x <- [1,2], y <- " ciao "] -- => [(1, c ),(1, i ),(1, a ),(1, o ), (2, c ),(2, i ),(2, a ),(2, o )] Matteo Pradella Principles of Programming Languages, 3 May / 94

39 Infinite lists (cont.) 1 a list with all the Fibonacci numbers (note: tail is cdr, while head is car) fib = 1 : 1 : [a+b (a,b) <- zip fib ( tail fib )] Matteo Pradella Principles of Programming Languages, 3 May / 94

40 An exercise on infinite lists 1 knowing that 2 any :: (a -> Bool) -> [a] -> Bool 3 takewhile :: (a -> Bool) -> [a] -> [a] 4 what is the meaning of this code? isprime n = not. any (\ x - > mod n x == 0). takewhile (\x -> x^2 <= n) $ primelist primelist = 2 : [x x <- [3,5..], isprime x] 5 note: any (>0) [3,-3..(-30)] is true; takewhile (> 0) [3,-3..(-30)] is [ 3 ] Matteo Pradella Principles of Programming Languages, 3 May / 94

41 Error 1 bottom (aka ) is defined as bot = bot 2 all errors have value bot, a value shared by all types 3 error :: String -> a is strange because is polymorphic only in the output 4 the reason is that it returns bot (in practice, an exception is raised) Matteo Pradella Principles of Programming Languages, 3 May / 94

42 Pattern matching 1 the matching process proceeds top-down, left-to-right 2 patterns may have boolean guards sign x x > 0 = 1 x == 0 = 0 x < 0 = -1 3 _ stands for don t care 4 e.g. definition of take take 0 _ = [] take _ [] = [] take n (x:xs) = x : take (n -1) xs Matteo Pradella Principles of Programming Languages, 3 May / 94

43 Take and definition 1 the order of definitions matters: Prelude> :t bot bot :: t Prelude> take 0 bot [] 2 on the other hand, take bot [] does not terminate 3 what does it change, if we swap the first two defining equations? Matteo Pradella Principles of Programming Languages, 3 May / 94

44 Case 1 take with case: take m ys = case (m,ys) of (0,_) -> [] (_,[]) -> [] (n,x:xs) -> x : take (n -1) xs Matteo Pradella Principles of Programming Languages, 3 May / 94

45 let and where 1 let is like Scheme s let*: let x = 3 y = 12 in x+y -- => 15 2 where can be convenient to scope binding over equations, e.g.: powset set = powset set [[]] where powset [] out = out powset (e: set ) out = powset set ( out ++ [ e:x x <- out ]) 3 layout is like in Python, with meaningful whitespaces, but we can also use a C-like syntax: let {x = 3 ; y = 12} in x+y Matteo Pradella Principles of Programming Languages, 3 May / 94

46 Call-by-need and memory usage 1 fold-left is efficient in Scheme, because its definition is naturally tail-recursive: foldl f z [] = z foldl f z (x:xs) = foldl f (f z x) xs 2 note: in Racket it is defined with (f x z) 3 this is not as efficient in Haskell, because of call-by-need: 1 foldl (+) 0 [1,2,3] 2 foldl (+) (0 + 1) [2,3] 3 foldl (+) ((0 + 1) + 2) [ 3 ] 4 foldl (+) (((0 + 1) + 2) + 3) [] 5 (((0 + 1) + 2) + 3) = 6 Matteo Pradella Principles of Programming Languages, 3 May / 94

47 Haskell is too lazy: an interlude on strictness 1 There are various ways to enforce strictness in Haskell (analogously there are classical approaches to introduce laziness in strict languages) 2 e.g. on data with bang patterns (a datum marked with! is considered strict) data Complex = Complex! Float! Float 3 there are extensions for using! also in function parameters Matteo Pradella Principles of Programming Languages, 3 May / 94

48 Forcing evaluation 1 Canonical operator to force evaluation is seq :: a -> t -> t 2 seq x y returns y, only if the evaluation of x terminates (i.e. it performs x then returns y) 3 a strict version of foldl (available in Data.List) foldl f z [] = z foldl f z (x:xs) = let z = f z x in seq z ( foldl f z xs) 4 strict versions of standard functions are usually primed Matteo Pradella Principles of Programming Languages, 3 May / 94

49 Special syntax for seq 1 There is a convenient strict variant of $ (function application) called $! 2 here is its definition: ($!) :: (a -> b) -> a -> b f $! x = seq x (f x) Matteo Pradella Principles of Programming Languages, 3 May / 94

50 Modules 1 not much to be said: Haskell has a simple module system, with import, export and namespaces 2 a very simple example module CartProd where --- export everything infixr 9 -*- -- right associative -- precedence goes from 0 to 9, the strongest x -*- y = [(i,j) i <- x, j <- y] Matteo Pradella Principles of Programming Languages, 3 May / 94

51 Modules (cont.) 1 import/export module Tree ( Tree ( Leaf, Branch ), fringe ) where data Tree a = Leaf a Branch ( Tree a) ( Tree a) fringe :: Tree a -> [a]... module Main ( main ) where import Tree ( Tree ( Leaf, Branch ) ) main = print ( Branch ( Leaf a ) ( Leaf b )) Matteo Pradella Principles of Programming Languages, 3 May / 94

52 Modules and Abstract Data Types 1 modules provide the only way to build abstract data types (ADT) 2 the characteristic feature of an ADT is that the representation type is hidden: all operations on the ADT are done at an abstract level which does not depend on the representation 3 e.g. a suitable ADT for binary trees might include the following operations: data Tree a -- just the type name leaf :: a -> Tree a branch :: Tree a -> Tree a -> Tree a cell :: Tree a -> a left, right :: Tree a -> Tree a isleaf :: Tree a -> Bool Matteo Pradella Principles of Programming Languages, 3 May / 94

53 ADT implementation module TreeADT ( Tree, leaf, branch, cell, left, right, isleaf ) where data Tree a = Leaf a Branch ( Tree a) ( Tree a) leaf = Leaf branch = Branch cell ( Leaf a) = a left ( Branch l r) = l right ( Branch l r) = r isleaf ( Leaf _) = True isleaf _ = False 1 in the export list the type name Tree appears without its constructors 1 so the only way to build or take apart trees outside of the module is by using the various (abstract) operations 2 the advantage of this information hiding is that at a later time we could change the representation type without affecting users of the type Matteo Pradella Principles of Programming Languages, 3 May / 94

54 Hoogle 1 it is Haskell s "google": a search engine for functions and libraries useful to find e.g. types, and where a function is defined Matteo Pradella Principles of Programming Languages, 3 May / 94

55 Type classes and overloading 1 we already saw parametric polymorphism in Haskell (e.g. in length) 2 type classes are the mechanism provided by Haskell for ad hoc polymorphism (aka overloading) 3 the first, natural example is that of numbers: 6 can represent an integer, a rational, a floating point number... 4 e.g. Prelude > 6 :: Float 6.0 Prelude > 6 :: Integer -- unlimited 6 Prelude > 6 :: Int -- fixed precision 6 Prelude > 6 :: Rational 6 % 1 Matteo Pradella Principles of Programming Languages, 3 May / 94

56 Type classes: equality 1 also numeric operators and equality work with different kinds of numbers 2 let s start with equality: it is natural to define equality for many types (but not every one, e.g. functions - it s undecidable) 3 we consider here only value equality, not pointer equality (like Java s == or Scheme s eq?), because pointer equality is clearly not referentially transparent 4 let us consider elem x elem [] = False x elem (y:ys) = x==y (x elem ys) 5 its type should be: a -> [a] -> Bool. But this means that (==) :: a -> a -> Bool, even though equality is not defined for every type Matteo Pradella Principles of Programming Languages, 3 May / 94

57 class Eq 1 type classes are used for overloading: a class is a "container" of overloaded operations 2 we can declare a type to be an instance of a type class, meaning that it implements its operations 3 e.g. class Eq class Eq a where (==) :: a -> a -> Bool 4 now the type of (==) is (==) :: (Eq a) => a -> a -> Bool 5 Eq a is a constraint on type a, it means that a must be an instance of Eq Matteo Pradella Principles of Programming Languages, 3 May / 94

58 Defining instances 1 e.g. elem has type (Eq a) => a -> [a] -> Bool 2 we can define instances like this: instance (Eq a) => Eq (Tree a) where -- type a must support equality as well Leaf a == Leaf b = a == b (Branch l1 r1) == (Branch l2 r2) = (l1==l2) && (r1==r2) _ == _ = False 3 an implementation of (==) is called a method 4 CAVEAT do not confuse all these concepts with the homonymous concepts in OO programming: there are similarities but also big differences Matteo Pradella Principles of Programming Languages, 3 May / 94

59 Haskell vs Java concepts 1 Haskell Java Class Interface Type Class Value Object Method Method 2 in Java, an Object is an instance of a Class 3 in Haskell, a Type is an instance of a Class Matteo Pradella Principles of Programming Languages, 3 May / 94

60 Eq and Ord in the Prelude 1 Eq offers also a standard definition of, derived from (==): class Eq a where (==), (/=) :: a -> a -> Bool x /= y = not (x == y) 2 we can also extend Eq with comparison operations: class (Eq a) => Ord a where (<), (<=), (>=), (>) :: a -> a -> Bool max, min :: a -> a -> a 3 Ord is also called a subclass of Eq 4 it is possible to have multiple inheritance: class (X a, Y a) => Z a Matteo Pradella Principles of Programming Languages, 3 May / 94

61 Another important class: Show 1 it is used for showing: to have an instance we must implement show 2 e.g., functions do not have a standard representation: Prelude> (+) <interactive>:2:1: No instance for (Show (a0 -> a0 -> a0)) arising from a use of print Possible fix: add an instance declaration for (Show (a0 -> a0 -> a0)) 3 well, we can just use a trivial one: instance Show (a -> b) where show f = "<< a function >>" Matteo Pradella Principles of Programming Languages, 3 May / 94

62 Showing Trees 1 we can also represent binary trees: instance Show a => Show (Tree a) where show (Leaf a) = show a show (Branch x y) = "<" ++ show x ++ " " ++ show y ++ ">" 2 e.g. Branch (Branch (Leaf a ) (Branch (Leaf b ) (Leaf c ))) (Branch (Leaf d ) (Leaf e )) 3 is represented as << a < b c >> < d e >> Matteo Pradella Principles of Programming Languages, 3 May / 94

63 Deriving 1 usually it is not necessary to explicitly define instances of some classes, e.g. Eq and Show 2 Haskell can be quite smart and do it automatically, by using deriving 3 for example we may define binary trees using an infix syntax and automatic Eq, Show like this: infixr 5 :^: data Tr a = Lf a Tr a :^: Tr a deriving (Show, Eq) 4 e.g. *Main> let x = Lf 3 :^: Lf 5 :^: Lf 2 *Main> let y = (Lf 3 :^: Lf 5) :^: Lf 2 *Main> x == y False *Main> x Lf 3 :^: (Lf 5 :^: Lf 2) Matteo Pradella Principles of Programming Languages, 3 May / 94

64 An example with class Ord 1 Rock-paper-scissors in Haskell data RPS = Rock Paper Scissors deriving (Show, Eq) instance Ord RPS where x <= y x == y = True Rock <= Paper = True Paper <= Scissors = True Scissors <= Rock = True _ <= _ = False 2 note that we only needed to define (<=) to have the instance Matteo Pradella Principles of Programming Languages, 3 May / 94

65 An example with class Num 1 a simple re-implementation of rational numbers data Rat = Rat!Integer!Integer deriving Eq simplify (Rat x y) = let g = gcd x y in Rat (x div g) (y div g) makerat x y = simplify (Rat x y) instance Num Rat where (Rat x y) + (Rat x y ) = makerat (x*y +x *y) (y*y ) (Rat x y) - (Rat x y ) = makerat (x*y -x *y) (y*y ) (Rat x y) * (Rat x y ) = makerat (x*x ) (y*y ) abs (Rat x y) = makerat (abs x) (abs y) signum (Rat x y) = makerat (signum x * signum y) 1 frominteger x = makerat x 1 Matteo Pradella Principles of Programming Languages, 3 May / 94

66 An example with class Num (cont.) 1 Ord: instance Ord Rat where (Rat x y) <= (Rat x y ) = x*y <= x *y 2 a better show: instance Show Rat where show (Rat x y) = show x ++ "/" ++ show y 3 note: Rationals are in the Prelude! 4 moreover, there is class Fractional for / (not covered here) 5 but we could define our version of division as follows: x // (Rat x y ) = x * (Rat y x ) Matteo Pradella Principles of Programming Languages, 3 May / 94

67 Input/Output is dysfunctional 1 what is the type of the standard function getchar, that gets a character from the user? getchar :: theuser -> Char? 2 first of all, it is not referentially transparent: two different calls of getchar could return different characters 3 In general, IO computation is based on state change (e.g. of a file), hence if we perform a sequence of operations, they must be performed in order (and this is not easy with call-by-need) Matteo Pradella Principles of Programming Languages, 3 May / 94

68 Input/Output is dysfunctional (cont.) 1 getchar can be seen as a function :: Time -> Char. 2 indeed, it is an IO action (in this case for Input): getchar :: IO Char 3 quite naturally, to print a character we use putchar, that has type: putchar :: Char -> IO () 4 IO is an instance of the monad class, and in Haskell it is considered as an indelible stain of impurity Matteo Pradella Principles of Programming Languages, 3 May / 94

69 A very simple example of an IO program 1 main is the default entry point of the program (like in C) main = do { putstr "Please, tell me something>"; thing <- getline; putstrln $ "You told me \"" ++ thing ++ "\"."; } 2 special syntax for working with IO: do, <- 3 we will see its real semantics later, used to define an IO action as an ordered sequence of IO actions 4 "<-" (note: not =) is used to obtain a value from an IO action 5 types: main :: IO () putstr :: String -> IO () getline :: IO String Matteo Pradella Principles of Programming Languages, 3 May / 94

70 Command line arguments and IO with files 1 compile with e.g. ghc readfile.hs import System.IO import System.Environment readfile = do { args <- getargs; -- command line arguments handle <- openfile (head args) ReadMode; contents <- hgetcontents handle; -- note: lazy putstr contents; hclose handle; } main = readfile 2 readfile stuff.txt reads "stuff.txt" and shows it on the screen 3 hgetcontents reads lazily the contents of the file Matteo Pradella Principles of Programming Languages, 3 May / 94

71 Exceptions and IO 1 Of course, purely functional Haskell code can raise exceptions: head [], 3 div 0,... 2 but if we want to catch them, we need an IO action: 3 handle :: Exception e => (e -> IO a) -> IO a -> IO a; the 1st argument is the handler 4 Example: we catch the errors of readfile import Control.Exception import System.IO.Error... main = handle handler readfile where handler e isdoesnotexisterror e = putstrln "This file does not exist." otherwise = putstrln "Got a problem." Matteo Pradella Principles of Programming Languages, 3 May / 94

72 Another typical issue: state 1 the typical way of managing state in a purely functional language is by passing it around 2 i.e. if a function works on state, it will receive it as a parameter, and will return it among its outputs 3 we can easily see it with an example: let us consider again binary trees data Tree a = Leaf a Branch (Tree a) (Tree a) deriving (Show, Eq) Matteo Pradella Principles of Programming Languages, 3 May / 94

73 Stateless maptree & the Functor class 1 it is easy to write a map function working on tree nodes: maptree :: (a -> b) -> Tree a -> Tree b maptree f (Leaf a) = Leaf (f a) maptree f (Branch lhs rhs) = Branch (maptree f lhs) (maptree f rhs) 2 there is a class, called Functor, for containers (and more) which offer a map operation (called fmap) instance Functor Tree where fmap = maptree Matteo Pradella Principles of Programming Languages, 3 May / 94

74 State & maptree 1 If we want to number every node going from left to right, the previous function does not work 2 indeed, we have to maintain a state in our visit of the tree: Matteo Pradella Principles of Programming Languages, 3 May / 94

75 Stateful maptree 1 adding state makes the function more complicated: maptreestate :: (a -> state -> (state, b)) -> Tree a -> state -> (state, Tree b) maptreestate f (Leaf a) state = let (state, b) = f a state in (state, Leaf b) maptreestate f (Branch lhs rhs) state = let (state, lhs ) = maptreestate f lhs state (state, rhs ) = maptreestate f rhs state in (state, Branch lhs rhs ) 2 note also that its type is getting hard to understand Matteo Pradella Principles of Programming Languages, 3 May / 94

76 Working with state on trees 1 Let s try it: testmts x st = (st+1, (x, st)) testtree = Branch (Branch (Leaf a ) (Branch (Leaf b ) (Leaf c ))) (Branch (Leaf d ) (Leaf e )) maptreestate testmts testtree 0 2 we get: (5, Branch (Branch (Leaf ( a,0)) (Branch (Leaf ( b,1)) (Leaf ( c,2)))) (Branch (Leaf ( d,3)) (Leaf ( e,4)))) 3 monads were introduced for managing more easily all these issues - but what is a monad? Matteo Pradella Principles of Programming Languages, 3 May / 94

77 A peculiar type class: Monad 1 introduced by Eugenio Moggi in 1991, a monad is a kind of algebraic data type used to represent computations (instead of data in the domain model) - we will often call these computations actions 2 monads allow the programmer to chain actions together to build an ordered sequence, in which each action is decorated with additional processing rules provided by the monad and performed automatically Matteo Pradella Principles of Programming Languages, 3 May / 94

78 A peculiar type class: Monad (cont.) 1 monads also can be used to make imperative programming easier in a pure functional language 2 in practice, through them it is possible to define an imperative sub-language on top of a purely functional one 3 there are many examples of monads and tutorials (many of them quite bad) available in the Internet 4 CAVEAT: don t panic! There is always a "scary theoretical taste" to many monadic concepts, taken from category theory, but in practice using and defining monads do not require a deep theoretical background Matteo Pradella Principles of Programming Languages, 3 May / 94

79 The Monad Class 1 first of all, Monad is a just type class: class Monad m where return :: a -> m a (>>=) :: m a -> (a -> m b) -> m b (>>) :: m a -> m b -> m b m >> k = m >>= \_ -> k -- default implementation fail :: String -> m a fail s = error s 2 >>= and >> are called bind -- default implementation 3 note that m is a type constructor, and m a is a type in the monad 4 moreover, m must be parametric with one parameter (see m a or m b in its definition). Matteo Pradella Principles of Programming Languages, 3 May / 94

80 The Monad Class (cont.) 1 m a is a computation (or action) resulting in a value of type a 2 return is used to create a single monadic action that actually does nothing. E.g. return 5 does nothing (as an action) and produces the value 5. 3 while bind operators are used to compose actions 1 x >>= y performs the computation x, takes the resulting value and passes it to y; then performs y. 2 x >> y is analogous, but "throws away" the value obtained by x Matteo Pradella Principles of Programming Languages, 3 May / 94

81 An example of standard monad: Maybe 1 Maybe is used to represent computations that may fail: we either have Just v, if we are lucky, or Nothing. data Maybe a = Nothing Just a instance Monad Maybe where return = Just fail s = Nothing Nothing >>= f = Nothing (Just x) >>= f = f x 2 It is adopted in many recent languages, to avoid e.g. exceptions. Examples are Scala (basically the ML family approach): Option[T], with values None or Some(v); Swift, with Optional<T>. Matteo Pradella Principles of Programming Languages, 3 May / 94

82 Examples with Maybe 1 The information managed automatically by the monad is the bit which encodes the success (i.e. Just) or failure (i.e. Nothing) of the action sequence 2 e.g. Just 4 >> Just 5 >> Nothing >> Just 6 evaluates to Nothing 3 a variant: Just 4 >>= Just >> Nothing >> Just 6 4 another: Just 4 >> Just 1 >>= Just (what is the result in this case?) Matteo Pradella Principles of Programming Languages, 3 May / 94

83 The monadic laws 1 for a monad to behave correctly, method definitions must obey the following laws: 2 1) return is the identity element: (return x) >>= f <=> f x m >>= return <=> m 3 2) associativity for binds: (m >>= f) >>= g <=> m >>= (\x -> (f x >>= g)) 4 (monads are analogous to monoids, with return = 1 and >>= = ) Matteo Pradella Principles of Programming Languages, 3 May / 94

84 Example: monadic laws application with Maybe 1 > (return 4 :: Maybe Integer) >>= \x -> Just (x+1) Just 5 > Just 5 >>= return Just 5 2 > (return 4 >>= \x -> Just (x+1)) >>= \x -> Just (x*2) Just 10 > return 4 >>= (\y -> ((\x -> Just (x+1)) y) >>= \x -> Just (x*2)) Just 10 Matteo Pradella Principles of Programming Languages, 3 May / 94

85 Syntactic sugar: the do notation 1 The do syntax is used to avoid the explicit use of >>= and >> 2 The essential translation of do is captured by the following two rules: do e1 ; e2 <=> e1 >> e2 do p <- e1 ; e2 <=> e1 >>= \p -> e2 3 note that they can also be written as: 4 or: do e1 e2 do p <- e1 e2 do { e1 ; do { p <- e1 ; e2 } e2 } Matteo Pradella Principles of Programming Languages, 3 May / 94

86 Caveat: return does not return 1 For example: esp :: IO Integer esp = do x <- return 4 return (x+1) *Main> esp 5 Matteo Pradella Principles of Programming Languages, 3 May / 94

87 Examples of built-in monads 1 List: monadic binding involves joining together a set of calculations for each value in the list 2 Given a list of a and a function f :: a b, >>= applies f to each of the a in the input, and returns all of the generated b put into a list 3 i.e. it is map, or, more precisely, concatmap concatmap :: (a -> [b]) -> [a] -> [b] *Main> concatmap (\x -> [x, x+1]) [1,2,3] [1,2,2,3,3,4] 4 return creates a singleton list Matteo Pradella Principles of Programming Languages, 3 May / 94

88 Lists: do vs comprehensions 1 list comprehensions are just syntax: 2 i.e. the following code [(x,y) x <- [1,2,3], y <- [1,2,3]] 3 is translated into: do x <- [1,2,3] y <- [1,2,3] return (x,y) Matteo Pradella Principles of Programming Languages, 3 May / 94

89 the List monad 1 definition: instance Monad [] where return x = [x] l >>= f = concatmap f l fail _ = [] Matteo Pradella Principles of Programming Languages, 3 May / 94

90 the List monad (cont.) 1 to understand our example of comprehension, i.e. testcomp = do x <- [1,2,3] y <- [1,2,3] return (x,y) 2 we can rewrite it following the monad definition: testcomp = [1,2,3] >>= (\x -> [1,2,3] >>= (\y -> return (x,y))) Matteo Pradella Principles of Programming Languages, 3 May / 94

91 the List monad (cont.) 1 that is: testcomp = concatmap f0 [1,2,3] where f0 x = concatmap f1 [1,2,3] where f1 y = [(x,y)] Matteo Pradella Principles of Programming Languages, 3 May / 94

92 Back to Data Structures 1 What about usual, practical data structures (e.g. arrays, hash-tables)? 2 Traditional versions are imperative! If really needed, there are libraries with imperative implementations living in the IO monad 3 Idiomatic approach: use immutable arrays (Data.Array), and maps (Data.Map, implemented with balanced binary trees) 4 find are respectively O(1) and O(log n); update O(n) for arrays, O(log n) for maps 5 of course, the update operations copy the structure, do not change it Matteo Pradella Principles of Programming Languages, 3 May / 94

93 Example code: Maps import Data.Map exmap = let m = fromlist [("nose", 11), ("emerald", 27)] n = insert "rug" 98 m o = insert "nose" 9 n in (m! "emerald", n! "rug", o! "nose") 1 exmap evaluates to (27,98,9) Matteo Pradella Principles of Programming Languages, 3 May / 94

94 Example code: Arrays 1 (//) is used for update/insert 2 listarray s first argument is the range of indexing (in the following case, indexes are from 1 to 3) import Data.Array exarr = let m = listarray (1,3) ["alpha","beta","gamma"] n = m // [(2,"Beta")] o = n // [(1,"Alpha"), (3,"Gamma")] in (m! 1, n! 2, o! 1) 3 exarr evaluates to ("alpha","beta","alpha") Matteo Pradella Principles of Programming Languages, 3 May / 94

95 Legal stuff & acknowledgments by Matteo Pradella Licensed under Creative Commons License, Attribution-ShareAlike 3.0 Unported (CC BY-SA 3.0) 1 Many examples were taken and adapted from: Hudak, Peterson, Fasel, A Gentle Introduction to Haskell 98, 1999 Matteo Pradella Principles of Programming Languages, 3 May / 94

Principles of Programming Languages (H)

Principles of Programming Languages (H) Principles of Programming Languages (H) Matteo Pradella December 1, 2017 Matteo Pradella Principles of Programming Languages (H) December 1, 2017 1 / 105 Overview 1 Introduction on purity and evaluation

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

User-Defined Algebraic Data Types

User-Defined Algebraic Data Types 72 Static Semantics User-Defined Types User-Defined Algebraic Data Types An algebraic data type declaration has the general form: data cx T α 1... α k = K 1 τ 11... τ 1k1... K n τ n1... τ nkn introduces

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

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

Haskell Monads CSC 131. Kim Bruce

Haskell Monads CSC 131. Kim Bruce Haskell Monads CSC 131 Kim Bruce Monads The ontological essence of a monad is its irreducible simplicity. Unlike atoms, monads possess no material or spatial character. They also differ from atoms by their

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

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

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

Box-and-arrow Diagrams

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

More information

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

JVM ByteCode Interpreter

JVM ByteCode Interpreter JVM ByteCode Interpreter written in Haskell (In under 1000 Lines of Code) By Louis Jenkins Presentation Schedule ( 15 Minutes) Discuss and Run the Virtual Machine first

More information

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

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

3. Functional Programming. Oscar Nierstrasz

3. Functional Programming. Oscar Nierstrasz 3. Functional Programming Oscar Nierstrasz Roadmap > Functional vs. Imperative Programming > Pattern Matching > Referential Transparency > Lazy Evaluation > Recursion > Higher Order and Curried Functions

More information

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

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

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

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

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

IO Monad (3D) Young Won Lim 1/18/18

IO Monad (3D) Young Won Lim 1/18/18 Copyright (c) 2016-2018 Young W. Lim. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later version published

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

Polymorphic lambda calculus Princ. of Progr. Languages (and Extended ) The University of Birmingham. c Uday Reddy

Polymorphic lambda calculus Princ. of Progr. Languages (and Extended ) The University of Birmingham. c Uday Reddy 06-02552 Princ. of Progr. Languages (and Extended ) The University of Birmingham Spring Semester 2016-17 School of Computer Science c Uday Reddy2016-17 Handout 6: Polymorphic Type Systems 1. Polymorphic

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

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

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

More information

Imperative languages

Imperative languages Imperative languages Von Neumann model: store with addressable locations machine code: effect achieved by changing contents of store locations instructions executed in sequence, flow of control altered

More information

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

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

More information

Haskell 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

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

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

Haskell through HUGS THE BASICS

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

More information

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

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

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

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

INDEX. Symbols & Numbers. Learn You a Haskell for Great Good! 2011 by Miran Lipovača

INDEX. Symbols & Numbers. Learn You a Haskell for Great Good! 2011 by Miran Lipovača INDEX Symbols & Numbers && (double ampersand) as Boolean operator conjunction, 2 using with folds and lists, 78 79 '(apostrophe) using with functions, 7 using with types, 149 150 * (asterisk) as multiplication

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

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

Introduction. chapter Functions

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

More information

CSCE 314 Programming Languages

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

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

Functional Programming Functional Programming Overview! Functional vs. imperative programming! Fundamental concepts! Evaluation strategies! Pattern matching! Higher order functions! Lazy lists References! Richard Bird, Introduction

More information

Introduction to Functional Programming and Haskell. Aden Seaman

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

More information

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

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

Lambda Calculus and Type Inference

Lambda Calculus and Type Inference Lambda Calculus and Type Inference Björn Lisper Dept. of Computer Science and Engineering Mälardalen University bjorn.lisper@mdh.se http://www.idt.mdh.se/ blr/ October 13, 2004 Lambda Calculus and Type

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

Software System Design and Implementation

Software System Design and Implementation Software System Design and Implementation Functional Programming Gabriele Keller The University of New South Wales School of Computer Science and Engineering Sydney, Australia COMP3141 16s1 Course software

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

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

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

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

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

A Gentle Introduction to Haskell 98

A Gentle Introduction to Haskell 98 A Gentle Introduction to Haskell 98 Paul Hudak Yale University Department of Computer Science Joseph H. Fasel University of California Los Alamos National Laboratory October, 1999 John Peterson Yale University

More information

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

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

More information

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

Haskell: yet another Functional Language. Distributed and Parallel Technology

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

More information

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

Chapter 11 :: Functional Languages

Chapter 11 :: Functional Languages Chapter 11 :: Functional Languages Programming Language Pragmatics Michael L. Scott Copyright 2016 Elsevier 1 Chapter11_Functional_Languages_4e - Tue November 21, 2017 Historical Origins The imperative

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

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

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

Principles of Programming Languages, Appendix

Principles of Programming Languages, Appendix Principles of Programming Languages, Appendix Matteo Pradella February 2015 Matteo Pradella Principles of Programming Languages, Appendix February 2015 1 / 69 1 Scheme 2 Haskell 3 Prolog Matteo Pradella

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

G Programming Languages Spring 2010 Lecture 6. Robert Grimm, New York University

G Programming Languages Spring 2010 Lecture 6. Robert Grimm, New York University G22.2110-001 Programming Languages Spring 2010 Lecture 6 Robert Grimm, New York University 1 Review Last week Function Languages Lambda Calculus SCHEME review 2 Outline Promises, promises, promises Types,

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

Functional Languages. CSE 307 Principles of Programming Languages Stony Brook University

Functional Languages. CSE 307 Principles of Programming Languages Stony Brook University Functional Languages CSE 307 Principles of Programming Languages Stony Brook University http://www.cs.stonybrook.edu/~cse307 1 Historical Origins 2 The imperative and functional models grew out of work

More information

Programming Languages

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

More information

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

CS 360: Programming Languages Lecture 12: More Haskell

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

More information

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

Types in Programming Languages Dynamic and Static Typing, Type Inference (CTM 2.8.3, EPL* 4) Abstract Data Types (CTM 3.7) Monads (GIH** 9)

Types in Programming Languages Dynamic and Static Typing, Type Inference (CTM 2.8.3, EPL* 4) Abstract Data Types (CTM 3.7) Monads (GIH** 9) Types in Programming Languages Dynamic and Static Typing, Type Inference (CTM 2.8.3, EPL* 4) Abstract Data Types (CTM 3.7) Monads (GIH** 9) Carlos Varela Rensselaer Polytechnic Institute September 23,

More information

Type Checking and Type Inference

Type Checking and Type Inference Type Checking and Type Inference Principles of Programming Languages CSE 307 1 Types in Programming Languages 2 Static Type Checking 3 Polymorphic Type Inference Version: 1.8 17:20:56 2014/08/25 Compiled

More information

CMSC 330: Organization of Programming Languages. OCaml Imperative Programming

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

More information

G Programming Languages - Fall 2012

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

More information

Intro to Haskell Notes: Part 5

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

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

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

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

CSCE 314 Programming Languages. Interactive Programming: I/O

CSCE 314 Programming Languages. Interactive Programming: I/O CSCE 314 Programming Languages Interactive Programming: I/O Dr. Hyunyoung Lee 1 Introduction To date, we have seen how Haskell can be used to write batch programs that take all their inputs at the start

More information

CS The IO Monad. Slides from John Mitchell, K Fisher, and S. Peyton Jones

CS The IO Monad. Slides from John Mitchell, K Fisher, and S. Peyton Jones CS 242 2012 The IO Monad Slides from John Mitchell, K Fisher, and S. Peyton Jones Reading: Tackling the Awkward Squad, Sections 1-2 Real World Haskell, Chapter 7: I/O Beauty... Functional programming is

More information

Haskell Revision and Exercises

Haskell Revision and Exercises and Exercises April 10, 2017 Martin Perešíni Haskell Revision and Exercises April 10, 2017 1 / 53 Content Content Content Haskell Revision Types and Typeclasses Types of Functions List of types Syntax

More information

CMSC 330: Organization of Programming Languages. OCaml Imperative Programming

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

More information

IO Monad (3C) Young Won Lim 1/6/18

IO Monad (3C) Young Won Lim 1/6/18 Copyright (c) 2016-2018 Young W. Lim. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later version published

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

CSCC24 Functional Programming Scheme Part 2

CSCC24 Functional Programming Scheme Part 2 CSCC24 Functional Programming Scheme Part 2 Carolyn MacLeod 1 winter 2012 1 Based on slides from Anya Tafliovich, and with many thanks to Gerald Penn and Prabhakar Ragde. 1 The Spirit of Lisp-like Languages

More information