Programming Paradigms Functional languages

Size: px
Start display at page:

Download "Programming Paradigms Functional languages"

Transcription

1 Programming Paradigms Functional languages Ing. Marek Běhálek Ph.D. FEI VŠB-TUO EA404 / marek.behalek@vsb.cz Presentation is based on original course materials from doc. Ing Miroslav Beneš Ph.D.

2 Introduction Why functional programming maters Functional languages provides a framework in which the crucial ideas of modern programming are presented in clearest possible way. Functional languages are increasingly being used as components of larger systems. Declarative style of programming Why to learn functional programming? Simple model of programming New ideas and different approaches Our lectures will be: Simplified not all aspects (mainly theoretical) will be explored. Practically focused we will use Haskell We will (not strictly) follow: Thompson S.: Haskell: The Craft of Functional Programming Functional programming 2

3 Introduction Basic concepts (1) Function Gives output values based on input values A result based on parameters or arguments A process of giving particular inputs is called functional application Example Function giving distance between two cities. Functions evaluation You know how to evaluate an expression: (7-3)*2 In functional programming A program is a set of definitions of functions and other values These definitions model our particular problem. We evaluate them to obtain results. Definitions name :: Type name = expression Functional programming 3

4 Introduction Basic concepts (2) Function definitions square :: Int -> Int - declaration, must not be given! square n = n * n square applications square 5 = 5 * 5 square (2+4) = (2+4) * (2+4) Function composition Output of one function becomes input of another one. Powerful abstraction mechanism rotate :: Picture -> Picture rotate = fliph. flipv alternatively: rotate x = fliph (flipv x). is operator (like for example +) Type checking Definitions express a constrains, can lead to type error. Functional programming 4

5 Haskell Hugs (1) We will use Hugs98 Nearly full implementation of programming language Haskell 98 Some extension implemented Basic resources Language specification and other resources Installation packages (Win / Unix) User s manual (is a part of installation) Functional programming 5

6 Haskell Hugs (2) Basic evaluation: calculator $ hugs Prelude> 2*(3+5) 16 Script: containing user s definitions $ hugs example.hs Editing of source code :edit [file.hs] :e Loading of source code :load [file.hs] :reload Exiting work :quit Help :? Functional programming 6

7 Haskell Hugs (3) example.hs module Example where -- Function computing sum of two numbers sum x y = x + y Example.lhs > module Example where Function computing factorial > f n = if n == 0 then 1 else n * f (n-1) Functional programming 7

8 Haskell Hugs (4) Module has a name and contains definitions module Ant where Modules can be imported module Example where import Ant Prelude - similar to java.lang package. Hiding functions: import Prelude hiding (max, min) Functional programming 8

9 Haskell Hugs (5) Layout Indentations are important! Names Strange errors with ; funny x = x + 1 ERROR. : Syntax error in expression (unexpected ; ) Identifiers - begin with letter, followed by a sequence of letter digits, underscores and single quotes. Names used in definition of values begin with small letters. Types and constructors begins with capital letters. Functional programming 9

10 Haskell Basic data types 1::Int +, -, *, ^, div, mod, abs, negate, == mod infix version, we can use any function that way! a ::Char Special characters: \t, \n, \\, \, \ Prelude functions: ord :: Char -> Int, chr :: Int -> Char, toupper, isdigit Library Char True,False::Bool &&,, not, == 3.14::Float +, -, *, /, ^, **, ==, /=, <, >, <=, >= abs, acos, asin, sin, cos, celing, floor, exp, fromint, log, negate, pi signum Functional programming 10

11 Haskell Operators You can build new operators in Haskell Operators are build for operator s symbols:! # & $ % * + -. / < > =? \ ^ : ~ Similar to function definition (&&&) :: Int -> Int-> Int x &&& y = x +y Functional programming 11

12 Haskell Practical exercises (1) 1. Run Hugs 2. Evaluate expression (4+2)/(5-6) 3. Try to use different operators. 4. Create source file example.hs(lhs) 5. Implement function square :: Int -> Int Use its type definition, then remove it and observe differences in behavior. 6. Implement function sum :: Int -> Int -> Int, hides existing one in module Prelude. 7. Create function complex_computation that will be a composition of functions square and sum. 8. Use this function in infix notation. 9. Define your own operator for complex_computation. 10. Try to find what is operator $$ for. Functional programming 12

13 Haskell Programming in Haskell How to write programs in Haskell? Recursion Simple examples: factorial, Fibonacci numbers. Function definition revisited Guard expressions max :: Int -> Int -> Int max x y x>=y = x otherwise = y Conditional expression if condition then m else n It is expression not a statement! Functional programming 13

14 Haskell Pattern matching Equation and pattern unification (pattern matching): f pat11 pat12... = rhs1 f pat21 pat22... = rhs2... First corresponding equation is chosen. If there is none error Functional programming 14

15 Haskell Examples Factorial fakt1 n = if n == 0 then 1 else n * fakt1 (n-1) fakt2 0 = 1 fakt2 n = n * fakt2 (n-1) fakt3 0 = 1 fakt3 (n+1) = (n+1) * fakt3 n fakt4 n n == 0 = 1 otherwise = n * fakt4 (n-1) Fibonacci numbers fib :: Int -> Int fib 0 = 0 fib 1 = 1 fib (n+2) = fib n + fib (n+1) Functional programming 15

16 Haskell Practical exercises (2) 1. Create a function computing Fibonacci numbers, consider different possibilities. 2. Create a function computing: 1. remainder; 2. divider; 3. smallest common divider; Functional programming 16

17 Haskell List and tuples (1) List and tuples are basic concepts to building complex data structures. Important note - polymorphism and high order functions Ordered tuples (a,b,c,...) (1,2) :: (Int,Int) (1,['a','b'])::(Int, [Char]) () :: () We can use functions: fst (1,2) = 1 Pattern matching very usefull. Consider example: fibstep :: (Int, Int) -> (Int, Int) fibstep (u,v) = (v,u+v) fibpair :: Int -> (Int,Int) fibpair n n==0 = (0,1) otherwise = fibstep (fibpair (n-1)) newfib :: Int -> Int newfib = fst. fibpair Which one is faster? Functional programming 17

18 Haskell List and tuples (2) data List a = Cons a (List a) (x:xs) Nil [] : ( 2 : ( 3 : [ ] ) ) Functional programming 18

19 Haskell List and tuples (3) Lists [a] Empty list [] Non-empty list (x:xs) 1:2:3:[] :: [Int] [1,2,3] :: [Int] We can even have a list of functions! Functions are first class values in Haskell! [fib, newfib] :: [(Int -> Int)] List length length [] = 0 length (x:xs) = 1 + length xs Comment: be aware of name conflict with previously defined functions! Functional programming 19

20 Haskell Data types User defined data types data Color = Black White data Tree a = Leaf a Node a (Tree a) (Tree a) type String = [Char] type Table a = [(String, a)] Functional programming 20

21 Haskell Patterns variable inc x = x + 1 constant not True = False not False = True List length [] = 0 length (x:xs) = 1 + length xs tupels plus (x,y) = x+y User s type constructor nl (Leaf _) = 1 nl (Node _ l r) = (nl l) + (nl r) Named pattern s parts duphd p@(x:xs) = x:p Another patterns - n+k fact 0 = 1 fact (n+1) = (n+1)*fact n Functional programming 21

22 Haskell Practical exercises (3) 1. Create a function that computes length of a list. 2. Create a function that merge two lists into one list. 3. Create a function that merge two lists into one list of tuples. 4. Create a function that reverse a list. 5. Create a function that merges two lists into one using given function to merge specific elements together. Given lists: [1,2,3] [1,2,3] and operation *, the result should be [1,4,9]. 6. Create a function that product scalar multiplication if two vectors. 7. Create a function that compute Cartesian product of two vectors. 8. Create a function that find the smallest element in the list. Consider input restrictions. Functional programming 22

23 Haskell Type classes Type class set of types with specific operations Num: +, -, *, abs, negate, signum, Eq: ==, /= Ord: >, >=, <, <=, min, max Constrains, type class specification elem :: Eq a => a -> [a] -> Bool minimum :: Ord a => [a] -> a sum :: Num a => [a] -> a Functional programming 23

24 Haskell Endless lists ones = 1 : ones 1 natfrom n = n : natfrom (n+1) natfrom 1 = 1 : 2 : 3 : = [1..] How it is possible? Lazy evaluation, we will talk about it later Functional programming 24

25 Haskell Arithmetic rows [m..n] [1..5] = [1,2,3,4,5] [m1,m2..n] [1,3..10] = [1,3,5,7,9] [m..] [1..] = [1,2,3,4,5, ] [m1,m2..] [5,10..] = [5,10,15,20,25, ] Functional programming 25

26 Haskell List comprehensions Consider mathematic definitions Define a set containing even natural numbers smaller then or equal to 10. List comprehensions [n n <- [1..10], n mod 2 == 0] List generator: n <- [1..10] Examples: alleven xs = (xs == [x x<-xs, iseven x]) allodd xs = (xs == [x x<-xs, not(iseven x]) cart_prod xs ys = [(x,y) x<-xs, y<-ys] Functional programming 26

27 Haskell Practical exercises (4) 1. Using list generators create a function that: doubles all elements in a list; converts all small letters in String into capitals; which returns the list of divisors of a positive integer; Which check that a positive integer is a prime number. 2. Using list generators create functions than compute mathematical operations for sets (union, intersection, subset, complement). 3. Database implementation Consider data types: type Person type Book type Database = String = String = [ (Person, Book)] Create functions: books :: Database -> Person -> [Book] borrowers :: Database -> Book -> [Person] borroved :: Database -> Book -> Bool numborroved :: Database -> Book -> Int makeloan :: Database -> Person -> Book -> Database returnloan :: Database-> Person -> Book -> Database Functional programming 27

28 Haskell List functions in Prelude (1) elem 1 [2,3,4] = False elem 2 [2,3,4] = True elem 3 [] = False elem _ [ ] elem x (y:ys) x == y = False = True otherwise = elem x ys What is the type of the function elem? elem :: a -> [a] -> Bool - No, consider type classes Functional programming 28

29 Haskell List functions in Prelude (2) Accessing list elements head [1,2,3] = 1 tail [1,2,3] = [2,3] last [1,2,3] = 3 init [1,2,3] = [1,2] [1,2,3]!! 2 = 3 null [] = True length [1,2,3] = 3 Functional programming 29

30 Haskell List functions in Prelude (3) Merging lists [1,2,3] ++ [4,5] = [1,2,3,4,5] concat [[1,2],[3],[4,5]] = [1,2,3,4,5] zip [1,2] [3,4,5] = [(1,3),(2,4)] zipwith (+) [1,2] [3,4] = [4,6] Computing with lists sum [1,2,3,4] = 10 product [1,2,3,4] = 24 minimum [1,2,3,4] = 1 maximum [1,2,3,4] = 4 Functional programming 30

31 Haskell List functions in Prelude (4) Taking part of a list take 3 [1,2,3,4,5] = [1,2,3] drop 3 [1,2,3,4,5] = [4,5] takewhile (> 0) [1,3,0,4] = [1,3] dropwhile (> 0) [1,3,0,4] = [0,4] filter (>0) [1,3,0,2,-1] = [1,3,2] Transforming a list reverse [1,2,3,4] = [4,3,2,1] map (*2) [1,2,3] = [2,4,6] Functional programming 31

32 Haskell Practical exercises (5) Consider following type representing picture: type Pic = [String] If you want to print this picture you can use: pp :: Pic -> IO () pp = putstr. concat. map (++"\n") Picture example: obr :: Pic obr = [ "...#...", "...###...", "..#.#.#..", ".#..#..#.", "...#...", "...#...", "...#####"] Create functions that: flips picture veriticaly and horizontaly; place one picture above another (considering they have the same width); place two pictures side by side (considering they have the same height); rotate picture to the left and to the right. Functional programming 32

33 Haskell Local definition Construction let... in f x y = let p z = x + y +z q = x y in ( p 5 )* q Construction where f x y = p * q where p = x + y q = x - y Functional programming 33

34 Haskell Example Example creating a list of squared numers dm [] = [] dm (x:xs) = sq x : dm xs where sq x = x * x List s ordering (quicksort) qs [] = [] qs (x:xs) = let ls = filter (< x) xs rs = filter (>=x) xs in qs ls ++ [x] ++ qs rs Functional programming 34

35 Haskell Scope of local definitions maxsq x y sqx > sqy = sqx otherwise = sqy where sqx = sq x sqy = sq y sq :: Int -> Int sq z = z*z maxsq x y sq x > sq y = sq x otherwise = sq y where sq x = x * x Functional programming 35

36 Haskell Practical exercises (6) Consider data in format: type Name type Price type BarCode = String = Int = Int type Database = [(BarCode, Name, Price)] type TillType = [BarCode] type BillType = [(Name,Price)] Create functions that produce a nice bill from lists of bar codes. Define a function returning line length. makebill :: TillType -> BillType formatbill :: BillType -> String producebill :: TillType -> String producebill = formatbill. makebill Functional programming 36

37 Haskell Pattern matching (conclusion) Patterns guard expression, functions also case expression firstdigit :: String -> Char firstdigit st = case (digit st) of [] -> 0 (x:_) -> x Summarized patterns a literal value 1, f a variable x, y a wildcard _ a tupple pattern a constructor pattern list, user defined type Functional programming 37

38 Haskell Example Insert sort isort :: [Int] -> [Int] isort [] = [] isort (x:xs) = ins x (isort xs) where ins :: Int -> [Int] -> [Int] ins x [] = [x] ins x (y:ys) x <= y = x : (y:ys) otherwise = y : ins x ys Functional programming 38

39 Haskell Practical exercises (7) Consider text in form: In computer science, functional programming is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids state and mutable data. It emphasizes the application of functions, in contrast to the imperative programming style, which emphasizes changes in state. We want to get justified text in form: In computer science, functional programming is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids state and mutable data. It emphasizes the application of functions, in contrast to the imperative programming style, which emphasizes changes in state. Notes: whitespace = [ \n, \t, ] linelength = 30 Functional programming 39

40 History Language and computer s architecture Languages are practically restricted by current hardware. Maybe a pitfall of functional languages in the past. Von Neumann s architecture Model of classics processors Give a background to some languages Functional languages Backus (1978, Turing Adward) criticism of a language development based on a computer architecture Functional languages are better then imperative languages in some cases. Prove program properties Easy to parallelize Base on algebraic rules But, to work at least nearly as effective as imperative languages nontrivial optimizations must be performed. On the other hand, who cares about performance any more Functional programming 40

41 Functional programming Summary - what we know yet Imperative languages Program has a state. We can modify a state using statements. Statements are executed in given order. Based on Von Neummans architecture - simple and effective integration. Declarative languages No implicit state. Program is composed from expressions not statements. Programs describes what to compute and it does not defines how. No execution order is given. Functions are first-class values. No side effects Excellent abstraction mechanisms High order functions. Function composition. No variables. Assignment has it original mathematical meaning Basic technique is recursion no cycles. Functional programming 41

42 λ-calculus - History 1930 Alonzo Church Untyped λ-calculus A formal system for function definition, function application and recursion. Functions are very crucial background of functional languages. Background for all functional languages. The λ-calculus provides simple semantics for computation with functions so that properties of functional computation can be studied. Functional programming 42

43 λ-calculus - Terms Variables x, y, z, f, g, λ-abstraction (e is also a term) λ x. e A Function with a parameter x and body e. λ x y. e Equivalent to λ x. (λ y. e) λ e. e (λ f x (f x x)) (λ f x (f x x)) Application (e 1 e 2 ) Application of a function e1 on an argument e2 (f x y) Application of a function (f x) on an argument y Application of a function f on arguments x a y Conventions of parentheses λx. λy. e 1 e 2 = (λx. (λy. e 1 e 2 )) e 1 e 2 e 3 = ((e 1 e 2 ) e 3 ) Functional programming 43

44 λ-calculus - Substitution e 1 [e 2 /x] Replace all occurrences of free variable x in term e 1 with term e 2 Substitution must be valid (free variable must not be bound in e 2 after the substitution) (λ x y. f x y) [g z / f] = λ x y. (g z) x y (λ x y. f x y) [g z / x] = λ x y. f x y (λ x y. f x y) [g y / f] =invalid substitution Functional programming 44

45 λ-calculus - Evaluation of expressions (1) α-reduction λ x. e λ y. e[ y / x ] Renaming of a bound variable Substitution must be valid β-reduction (λ x. e 1 ) e 2 e 1 [ e 2 / x ] call a function η-reduction λ x. f x f Removes abstraction Variable x must not be free. Functional programming 45

46 λ-calculus - Evaluation of expressions (2) ((λ f x. f x x) (λ x y. p y x)) = β λ x. (λ x y. p y x) x x = α λ z. (λ x y. p y x) z z = β λ z. (λ y. p y z) z = β λ z. p z z (λ f x. f x x) (λ x y. p y x) = η (λ f x. f x x) (λ y. p y) = η (λ f x. f x x) p = β λ x. p x x Functional programming 46

47 λ-calculus - Evaluation of expressions (3) redex --- reducible expression α-redex, β-redex Normal form Expression that contains no β-redex. Church-Rosser theorem states that lambda calculus as a reduction system with lambda conversion rules satisfies the Church-Rosser property. If e1 e2, then there is e such that e1 e and e2 e. Why is this important? Normal-order reduction is the evaluation strategy in which one continually applies the rule for beta reduction in head position until no more such reductions are possible. At that point, the resulting term is in head normal form. If a term has a head normal form, then normal order reduction will eventually reach it. In contrast, applicative order reduction may not terminate, even when the term has a normal form. Functional programming 47

48 λ-calculus - Evaluation of expressions (4) Lambda calculus: normal form - no redex Haskell: Practical aspects like: If the result is a function, we do not need to reduce its body. Usual forms: Normal form Weak normal form Weak head normal form Reduction strategies When we combine a mechanism for choosing the next redex (innermost or outermost) with a particular notion of normal form, we get a reduction strategy. Significant reduction strategies Call by name: outermost reduction to weak head normal form Normal order: outermost reduction to normal form Call by value: innermost reduction to weak normal form Applicative order: innermost reduction to normal form Functional programming 48

49 λ-calculus - Evaluation of expressions (5) Function f is strict when and only when: f = Non-strict functions are often called lazy. Lazy evaluation Sub-expressions will be evaluated only when they are needed for in evaluation. Basic elements are: 1. Arguments are evaluated only if they are needed. 2. Arguments are evaluated only once. Add1 solves normal order Call by need As normal order, but function applications that would duplicate terms instead name the argument, which is then reduced only "when it is needed. Non-strict evaluation For functional languages it is lazy evaluation. Functional programming 49

50 Functional languages - Reasoning about programs (1) Ok, functional languages have mathematical background, but is this any good for me (while I am a programmer)? Consider possibility to reason about programs properties. Mathematic induction (informally) a) Prove for n = 0 (base case) b) On assumption that it holds for n, prove that it holds for n+1 Principle of structural induction for lists we want to prove property P a) Base case prove P for [] outright. b) Prove P (x:xs) on assumption that P(xs) holds. Functional programming 50

51 Functional languages - Reasoning about programs (2) (xs ++ ys) ++ zs = xs ++ (ys ++ zs) [] ++ ys = ys (++.1) (x:xs) ++ ys = x: (xs ++ ys) (++.2) a) [ ] => xs ([] ++ ys) ++ zs = ys ++ zs (++.1) = [] ++ (ys ++ zs) (++.1) Functional programming 51

52 Functional languages - Reasoning about programs (3) (xs ++ ys) ++ zs = xs ++ (ys ++ zs) [] ++ ys = ys (++.1) (x:xs) ++ ys = x: (xs ++ ys) (++.2) b) (x:xs) => xs ((x:xs)++ys)++zs = x:(xs++ys)++zs (++.2) = x:((xs++ys)++zs) (++.2) = x:(xs++(ys++zs)) (assumption) = (x:xs)++(ys++zs) (++.2) Functional programming 52

53 Functional languages - Reasoning about programs (4) length (xs++ys) = length xs + length ys length [] = 0 (len.1) length (_:xs) = 1 + length xs (len.2) a) [] => xs length ([] ++ ys) = length ys (++.1) = 0 + length ys (zero element for +) = length [] + length ys (len.1) Functional programming 53

54 Functional languages - Reasoning about programs (5) length (xs++ys) = length xs + length ys length [] = 0 (len.1) length (_:xs) = 1 + length xs (len.2) b) (x:xs) => xs length ((x:xs) ++ ys) = length (x:(xs++ys) (++.2) = 1 + length (xs++ys) (len.2) = 1 + (length xs + length ys) (assumption) = (1 + length xs) + length ys (associativity of +) = length (x:xs) + length ys (len.2) Functional programming 54

55 Haskell Functions as values (revisited 1) Function can be argument, but functions can also be results of a computation. Functions composition (f. g) x= f (g x) Composition is associative. Consider order of operations: not. not True leads to an error! Function as a result twice f = (f. f) Partial application inc x = 1 + x inc x = add 1 x inc = add 1 inc = (+1) = (1+) add = (+) Point free programming lcasestring s = map tolower s lcasestring = map tolower Functional programming 55

56 Haskell Functions as values (revisited 2) Lambda abstraction: \ x -> e λx. e inc = \x -> x+1 plus = \(x,y) -> x + y dividers n = filter (\m -> n `mod` m == 0) [1..n] Using lambda abstraction like a parameter nonzero xs = filter p xs where p x = x /= 0 nonzero xs = filter (/= 0) xs nonzero xs = filter (\x -> x/=0) xs Currying and uncurrying curry :: ((a,b)->c) -> (a->b->c) curry g x y = g (x,y) uncurry :: (a->b->c) -> ((a,b)->c) Uncurry f (x,y) = f x y Functional programming 56

57 Haskell Practical exercises (8) Consider text in form: In computer science, functional programming is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids state and mutable data. It emphasizes the application of functions, in contrast to the imperative programming style, which emphasizes changes in state. We want to automatically make an index. Only words at least 4 letters long will be indexed. Words in index are alphabetically ordered. Index will be a line number. Notes: whitespace = [ \n, \t, ] Functional programming 57

58 Haskell Introducing classes (1) Remember elem function elem :: a->[a]->bool What is its type? Is it ok? Defining type a class class Eq a where (==) :: a -> a -> Bool Using type classes elem :: Eq a => a -> [a] -> Bool What about the definition of ==? I need to compare bools, integers,? Instances of type classes instance Eq Bool where True == True = True False == False = True _ == _ = False Functional programming 58

59 Haskell Introducing classes (2) Default definitions class Eq a where (==), (/=) :: a -> a -> Bool x == y = not (x/=y) x /= y = not (x == y) Default definitions are overridden by instance definition. At least one must be defined. Derived classes class Eq a => Ord a where (<), (<=), (>), (>=) :: a -> a -> Bool max, min :: a -> a -> a compare :: a -> a -> Ordering Class Ord inherits the operations from class Eq. Functional programming 59

60 Haskell Introducing classes (3) User defined classes class Visible a where tostring :: a -> String size :: a -> Int instance Visible Char where tostring ch = [ch] size _ = 1 Instance Visible Bool where tostring True = True tostring False = False size = length. tostring Defining context instance Visible a => Visible [a] where tostring = concat. map tostring size = foldr (+) 0. map size Multiple constrains vsort :: (Ord a, Visible a) => [a] -> String class (Ord a, Visible a) => OrdVisible a where Functional programming 60

61 Haskell Basic type classes (1) Eq a (==), (/=) Eq a => Ord a (<), (<=), (>), (>=), min, max Enum a Read a Show a (Eq a, Show a) => Num a (Num a) => Fractional a (Fractional a) => Floating a succ, pred readsprec showspres, show (+), (-), (*), negate, abs (/), recip pi, exp, log, sqrt, (**), Functional programming 61

62 Haskell Basic type classes (2) Functional programming 62

63 Haskell Show Values convertible to text type ShowS = String -> String class Show a where showsprec :: Int -> a -> ShowS show :: a -> String showlist :: [a] -> ShowS showpoint :: Point -> String showpoint (Pt x,y) = ( ++ show x ++ ; ++ show y ++ ) instance Show Point where show p = showpoint p Functional programming 63

64 Haskell Practical exercises (9) Define class Visible. Define visibility for tuples. Make visible objects usable with function show. Functional programming 64

65 Haskell Algebraic types (1) data Color = Red Green Blue Color type constructor Red / Green / Blue data constructor, nullary constructor data Point = Point Float Float dist (Point x1 y1) (Point x2 y2) = sqrt ((x2-x1)**2 + (y2-y1)**2) dist (Point ) (Point ) = 5.0 data Point a = Point a a polymorphism Constructor: Point :: a -> a -> Point a Functional programming 65

66 Haskell Algebraic types (2) Recurrent data structures data List a = Null Cons a (List a) lst :: List Int lst = Cons 1 (Cons 2 (Cons 3 Null)) append Null ys = ys append (Cons x xs) ys = Cons x (append xs ys) Deriving instances of class data Shape = Circle Float Rectangle Float Float driving (Eq, Ord, Show) Functional programming 66

67 Haskell Algebraic types (3) Example: Tree data Tree1 a = Leaf a Branch (Tree1 a) (Tree1 a) data Tree2 a = Leaf a Branch a (Tree2 a) (Tree2 a) data Tree3 a = Null Branch a (Tree3 a) (Tree3 a) t2l (Leaf x) = [x] t2l (Branch lt rt) = (t2l lt) ++ (t2l rt) Functional programming 67

68 Haskell Practical exercises (10) Consider following representation of expressions data Expr = Num Int Add Expr Expr Sub Expr Expr Mul Expr Expr Div Expr Expr Var Char deriving (Eq) 1. Create function eval that evaluates expresions. 2. Create function showexpr that shows expression as a String. 3. Extend class Show to be usable with our expressions. 4. Create function derivation representing symbolic derivation of a given expression. Functional programming 68

69 Haskell Abstract Data Type Modules module A where -- A.hs, A.lhs All definitions are visible. Import module A where import B All visible definitions are imported. Restricted exportu module Expr ( printexpr, Expr(..) ) where Expr(..) exports also constructors Expr - exports data type name only Restricted import import Expr hiding( printexpr ) import qualified Expr -- Expr.printExpr import Expr as Vyraz -- Vyraz.printExpr Functional programming 69

70 Haskell ADT Queue (1) Initialization: emptyq Test if queue is empty: isemptyq Inserting new element at the end: addq Removing element from the beginning: remq module Queue ( Queue, emptyq, -- Queue a isemptyq, -- Queue a -> Bool addq, -- a -> Queue a -> Queue a remq -- Queue q -> (a, Queue a) ) where Functional programming 70

71 Haskell ADT Queue (2) newtype Queue a = Qu [a] emptyq = Qu [] isemptyq (Qu q) = empty q addq x (Qu xs) = Qu (xs++[x]) remq q@(qu xs) not (isemptyq q) = (head xs, Qu (tail xs)) otherwise = error remq Functional programming 71

72 Haskell ADT Queue (2) -- diferent possibility for implementation (reverse order in data representation) addq x (Qu xs) = Qu (x:xs) remq q@(qu xs) not (isemptyq q) = (last xs, Qu (init xs)) otherwise = error remq Consider complexity! Functional programming 72

73 Haskell Practical exercises (11) Create abstract data type Stack push :: a -> Stack a -> Stack a pop :: Stack a -> Stack a top :: Stack a -> a isempty :: Stack a ->Bool Functional programming 73

74 Haskell Lazy programming (1) (remainder) Function f is strict when and only when: f = Non-strict functions are often called lazy. Lazy evaluation Sub-expressions will be evaluated only when they are needed for in evaluation. Basic elements are: 1. Arguments are evaluated only if they are needed. 2. Arguments are evaluated only once. Add1 solves normal order Call by need As normal order, but function applications that would duplicate terms instead name the argument, which is then reduced only "when it is needed. Non-strict evaluation For functional languages it is lazy evaluation. Functional programming 74

75 Haskell Lazy programming (2) Data oriented programming Programming where complex data structures are constructed and manipulated. Example: 1. Build a list of numbers 1.. N 2. Take a power of each number. 3. Find the sum of the list. Solution solve n = sum (map (^4) [1..n]) How does the calculation proceed? Conclusion None of the intermediate lists is created! Functional programming 75

76 Haskell Programming with actions (1) Functional program consists of a list of definitions. What about input? Consider function returning int. inputint :: Int What will be a result of: inputdiff = inputint InputInt funny :: Int-> Int funny n = inputint + n When thinking about I/O it makes more sense to think about actions happening in sequence. Actions in Haskell Type: IO a Functional programming 76

77 Haskell Programming with actions (2) Read / Write character getchar :: IO Char putchar :: Char -> IO () One value type () significat is their I/O action no the result. Transforming value to a I/O action return :: a -> IO a Notation: do It is used to sequence I/O actions It is used to capture values returned by actions. ready :: IO Bool ready = do c <- getchar return (c == y ) Variables here do not change values, single assignment only! Functional programming 77

78 Haskell Programming with actions (3) Example iseof :: IO Bool while :: IO Bool -> IO () -> IO () while test action = do res <- test if res then do else return () copyinputtooutput :: IO () copyinputtooutput = while (do res <-iseof return (not res)) (do line <- getline putstr line) action while test action Functional programming 78

79 Haskell Programming with actions revisited (1) What is a monad? class Monad m where (>>=) :: m a -> (a -> m b) -> m b (>>) :: m a -> m b -> m b m >> k = m >>= \_ -> k return :: a -> m a fail :: String -> m a fail s = error s Functional programming 79

80 Haskell Programming with actions revisited (2) Tree data Tree a = Nil Node a (Tree a) (Tree a) Standard approach stree :: Tree Int -> Int stree Nil = 0 steee (Node n t1 t2) = n+ stree t1 + stree t2 Monadic approach sumtree :: Tree Int -> St Int sumtree Nil = return 0 sumtree (Node n t1 t2) = do num <-return n s1 <- sumtree t1 s2 <- sumtree t2 return (num+s1+s2) Functional programming 80

81 Haskell Programming with actions revisited (2) Identity monad data Id a = Id a instance Monad Id where return = Id (>>=) (Id x) f = f x Extracting value from identity monad extract :: Id a -> a extract (Id x) = x Functional programming 81

82 Haskell Main function Starts the computation Action returning nothing. main :: IO () main = do c <- getchar putchar c Functional programming 82

83 Haskell Using actions printing a string We can apply a function putstr to every character. map putchar xs What will be a result type? map :: (a -> b) -> [a] -> [b] putchar :: Char -> IO () map putchar s :: [IO ()] Transforming into single action sequence :: [IO()] -> IO () putstr :: String -> IO () putstr s = sequence (map putchar s) Functional programming 83

84 Haskell Exceptions (1) Exceptions are instances of type IOError There is XXX function for every exception. isxxx :: IOError -> Bool iseoferror isdoesnotexisterror Throwing exception: function fail fail :: IOError -> IO a Results type is based on context. Catching exceptions: finction catch catch :: IO a -> (IOError -> IO a) -> IO a 1. First parameter is performed action. 2. Exceptions handler it is performed if the exception is thrown. 3. The result is first parameter if exception was not throwen. Functional programming 84

85 Haskell Exceptions (2) Function getchar ignoring all exceptions getchar = getchar `catch` ( \ _ -> return \n ) Function getchar handling EOF exception. getchar = getchar `catch` eofhandler where eofhandler e = if iseoferror e then return \n else fail e Functional programming 85

86 Haskell Working with files (1) type FilePath = String data IOMode = ReadMode WriteMode AppendMode ReadWriteMode data Handle openfile :: FilePath -> IOMode -> IO Handle hclose :: Handle -> IO () Functional programming 86

87 Haskell Working with files (2) stdin, stdout, stderr :: Handle hgetchar :: Handle -> IO Char getchar = hgetchar stdin Functions starting with h are using handlers. hgetcontents :: Handle -> String Read a whole content. Functional programming 87

88 Haskell Working with files (3) import IO main = do hin <- opf From: ReadMode hout <- opf To: WriteMode contents <- hgetcontents hin hputstr hout contents hclose hout putstr Done. opf :: String -> IOMode -> IO Handle opf prompt mode = do putstr prompt name <- getline openfile name mode Functional programming 88

89 Haskell Working with files (3) Function opf opens a file. If it can not be opened then it prints a message. opf prompt mode = do putstr prompt name <- getline catch (openfile name mode) (\_ -> do putstr ( Open error\n ) opf prompt mode) Functional programming 89

90 Haskell Practical exercises (12) Create a program that reads a file and number it s lines. 1) Transform a text to lines text2lines :: String -> [String] 2) Numbers lines. numbering :: [String] -> [String] 3) Transforms a list of lines to one string lines2text :: [String] -> String (lines2text. numbering. text2lines) contents Functional programming 90

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

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

Haske k ll An introduction to Functional functional programming using Haskell Purely Lazy Example: QuickSort in Java Example: QuickSort in Haskell

Haske k ll An introduction to Functional functional programming using Haskell Purely Lazy Example: QuickSort in Java Example: QuickSort in Haskell Haskell An introduction to functional programming using Haskell Anders Møller amoeller@cs.au.dk The most popular purely functional, lazy programming language Functional programming language : a program

More information

An introduction introduction to functional functional programming programming using usin Haskell

An introduction introduction to functional functional programming programming using usin Haskell An introduction to functional programming using Haskell Anders Møller amoeller@cs.au.dkau Haskell The most popular p purely functional, lazy programming g language Functional programming language : a program

More information

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

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

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

Lecture 2: List algorithms using recursion and list comprehensions

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

More information

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

IO Monad (3C) Young Won Lim 8/23/17

IO Monad (3C) Young Won Lim 8/23/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

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

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

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

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

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

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

More information

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

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

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

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

Shell CSCE 314 TAMU. Functions continued

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

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

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

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

Functional Programming

Functional Programming Functional Programming COMS W4115 Prof. Stephen A. Edwards Spring 2003 Columbia University Department of Computer Science Original version by Prof. Simon Parsons Functional vs. Imperative Imperative programming

More information

PROGRAMMING IN HASKELL. CS Chapter 6 - Recursive Functions

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

More information

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

CS 320: Concepts of Programming Languages

CS 320: Concepts of Programming Languages CS 320: Concepts of Programming Languages Wayne Snyder Computer Science Department Boston University Lecture 06: Useful Haskell Syntax, HO Programming Continued o Goodbye to Bare Bones Haskell: Built-in

More information

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

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

Exercise 1 ( = 22 points)

Exercise 1 ( = 22 points) 1 Exercise 1 (4 + 3 + 4 + 5 + 6 = 22 points) The following data structure represents polymorphic lists that can contain values of two types in arbitrary order: data DuoList a b = C a (DuoList a b) D b

More information

A tour of the Haskell Prelude

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

More information

Haskell 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

Functional Programming in Haskell Part I : Basics

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

More information

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

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

LECTURE 16. Functional Programming

LECTURE 16. Functional Programming LECTURE 16 Functional Programming WHAT IS FUNCTIONAL PROGRAMMING? Functional programming defines the outputs of a program as a mathematical function of the inputs. Functional programming is a declarative

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

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

Functional Programming TDA 452, DIT 142

Functional Programming TDA 452, DIT 142 Chalmers Göteborgs Universitet 2018-01-11 Examiner: Thomas Hallgren, D&IT, Answering questions at approx 15.00 (or by phone) Functional Programming TDA 452, DIT 142 2018-01-11 14.00 18.00 Samhällsbyggnad

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

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

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

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

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

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

Functional Programming. Big Picture. Design of Programming Languages

Functional Programming. Big Picture. Design of Programming Languages Functional Programming Big Picture What we ve learned so far: Imperative Programming Languages Variables, binding, scoping, reference environment, etc What s next: Functional Programming Languages Semantics

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

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

Exercise 1 ( = 18 points)

Exercise 1 ( = 18 points) 1 Exercise 1 (4 + 5 + 4 + 5 = 18 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 = Leaf

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

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

CS 11 Haskell track: lecture 1

CS 11 Haskell track: lecture 1 CS 11 Haskell track: lecture 1 This week: Introduction/motivation/pep talk Basics of Haskell Prerequisite Knowledge of basic functional programming e.g. Scheme, Ocaml, Erlang CS 1, CS 4 "permission of

More information

Functional Programming in Haskell Part 2 : Abstract dataypes and infinite structures

Functional Programming in Haskell Part 2 : Abstract dataypes and infinite structures Functional Programming in Haskell Part 2 : Abstract dataypes and infinite structures Madhavan Mukund Chennai Mathematical Institute 92 G N Chetty Rd, Chennai 600 017, India madhavan@cmi.ac.in http://www.cmi.ac.in/

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

CITS3211 FUNCTIONAL PROGRAMMING

CITS3211 FUNCTIONAL PROGRAMMING CITS3211 FUNCTIONAL PROGRAMMING 9. The λ calculus Summary: This lecture introduces the λ calculus. The λ calculus is the theoretical model underlying the semantics and implementation of functional programming

More information

Functional Programming

Functional Programming Functional Programming CS331 Chapter 14 Functional Programming Original functional language is LISP LISt Processing The list is the fundamental data structure Developed by John McCarthy in the 60 s Used

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

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

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

Functional Programming and λ Calculus. Amey Karkare Dept of CSE, IIT Kanpur

Functional Programming and λ Calculus. Amey Karkare Dept of CSE, IIT Kanpur Functional Programming and λ Calculus Amey Karkare Dept of CSE, IIT Kanpur 0 Software Development Challenges Growing size and complexity of modern computer programs Complicated architectures Massively

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

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

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

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

Functional Programming TDA 452, DIT 142

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

More information

Abstract Data Types. Functional Programming and Reasoning. Dr Hans Georg Schaathun. University of Surrey. Spring 2010 Week 4

Abstract Data Types. Functional Programming and Reasoning. Dr Hans Georg Schaathun. University of Surrey. Spring 2010 Week 4 Abstract Data Types Functional Programming and Reasoning Dr Hans Georg Schaathun University of Surrey Spring 2010 Week 4 Dr Hans Georg Schaathun Abstract Data Types Spring 2010 Week 4 1 / 32 Outline 1

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

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

Programming Language Concepts: Lecture 14

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

More information

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

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

Programming Language Pragmatics

Programming Language Pragmatics Chapter 10 :: Functional Languages Programming Language Pragmatics Michael L. Scott Historical Origins The imperative and functional models grew out of work undertaken Alan Turing, Alonzo Church, Stephen

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

Functional Programming and Haskell

Functional Programming and Haskell Functional Programming and Haskell Tim Dawborn University of Sydney, Australia School of Information Technologies Tim Dawborn Functional Programming and Haskell 1/22 What are Programming Paradigms? A programming

More information

PROGRAMMING IN HASKELL. Chapter 5 - List Comprehensions

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

More information

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

Introduction to the Lambda Calculus

Introduction to the Lambda Calculus Introduction to the Lambda Calculus Overview: What is Computability? Church s Thesis The Lambda Calculus Scope and lexical address The Church-Rosser Property Recursion References: Daniel P. Friedman et

More information

Principles of Programming Languages, 3

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

More information

I/O in Haskell. To output a character: putchar :: Char -> IO () e.g., putchar c. To output a string: putstr :: String -> IO () e.g.

I/O in Haskell. To output a character: putchar :: Char -> IO () e.g., putchar c. To output a string: putstr :: String -> IO () e.g. I/O in Haskell Generally, I/O functions in Haskell have type IO a, where a could be any type. The purpose and use of a will be explained later. We call these commands or actions, for we think of them as

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

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

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

Shell CSCE 314 TAMU. Higher Order Functions

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

More information

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

Programming Languages

Programming Languages Programming Languages Lambda Calculus and Scheme CSCI-GA.2110-003 Fall 2011 λ-calculus invented by Alonzo Church in 1932 as a model of computation basis for functional languages (e.g., Lisp, Scheme, ML,

More information

SML A F unctional Functional Language Language Lecture 19

SML A F unctional Functional Language Language Lecture 19 SML A Functional Language Lecture 19 Introduction to SML SML is a functional programming language and acronym for Standard d Meta Language. SML has basic data objects as expressions, functions and list

More information

M. Snyder, George Mason University LAMBDA CALCULUS. (untyped)

M. Snyder, George Mason University LAMBDA CALCULUS. (untyped) 1 LAMBDA CALCULUS (untyped) 2 The Untyped Lambda Calculus (λ) Designed by Alonzo Church (1930s) Turing Complete (Turing was his doctoral student!) Models functions, always as 1-input Definition: terms,

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

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

Functional Programming. Overview. Topics. Definition n-th Fibonacci Number. Graph Topics Functional Programming Christian Sternagel Harald Zankl Evgeny Zuenko Department of Computer Science University of Innsbruck WS 2017/2018 abstract data types, algebraic data types, binary search

More information

Graphical Untyped Lambda Calculus Interactive Interpreter

Graphical Untyped Lambda Calculus Interactive Interpreter Graphical Untyped Lambda Calculus Interactive Interpreter (GULCII) Claude Heiland-Allen https://mathr.co.uk mailto:claude@mathr.co.uk Edinburgh, 2017 Outline Lambda calculus encodings How to perform lambda

More information

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

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

More information

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

Programming Languages 3. Definition and Proof by Induction

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

More information

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

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

More information

Functional Programming Languages (FPL)

Functional Programming Languages (FPL) Functional Programming Languages (FPL) 1. Definitions... 2 2. Applications... 2 3. Examples... 3 4. FPL Characteristics:... 3 5. Lambda calculus (LC)... 4 6. Functions in FPLs... 7 7. Modern functional

More information

CSCE 314 Programming Languages

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

More information