0 PROGRAMMING IN HASKELL Chapter 11 - Interactive Programs, Declaring Types and Classes.

Slides:



Advertisements
Similar presentations
Kathleen Fisher cs242 Reading: “A history of Haskell: Being lazy with class”,A history of Haskell: Being lazy with class Section 6.4 and Section 7 “Monads.
Advertisements

0 PROGRAMMING IN HASKELL Chapter 10 - Declaring Types and Classes.
String is a synonym for the type [Char].
Functional Programming Universitatea Politehnica Bucuresti Adina Magda Florea
0 LECTURE 5 LIST COMPREHENSIONS Graham Hutton University of Nottingham.
Com Functional Programming Algebraic Data Types Marian Gheorghe Lecture 12 Module homepage Mole & ©University of.
What is a Parser? A parser is a program that analyses a piece of text to determine its syntactic structure  3 means 23+4.
0 PROGRAMMING IN HASKELL Chapter 5 - List Comprehensions.
Chapter 3 Simple Graphics. Side Effects and Haskell  All the programs we have seen so far have no “side-effects.” That is, programs are executed only.
0 PROGRAMMING IN HASKELL Chapter 4 - Defining Functions.
0 PROGRAMMING IN HASKELL Chapter 6 - Recursive Functions Most of this should be review for you.
0 PROGRAMMING IN HASKELL Chapter 6 - Recursive Functions.
Chapter 5 Polymorphic and Higher-Order Functions.
0 PROGRAMMING IN HASKELL Chapter 3 - Types and Classes.
0 PROGRAMMING IN HASKELL Chapter 9 - Interactive Programs.
PrasadCS7761 Haskell Data Types/ADT/Modules Type/Class Hierarchy Lazy Functional Language.
Haskell. 2 GHC and HUGS Haskell 98 is the current version of Haskell GHC (Glasgow Haskell Compiler, version 7.4.1) is the version of Haskell I am using.
0 PROGRAMMING IN HASKELL Based on lecture notes by Graham Hutton The book “Learn You a Haskell for Great Good” (and a few other sources) Modules.
0 REVIEW OF HASKELL A lightening tour in 45 minutes.
0 PROGRAMMING IN HASKELL Chapter 7 - Defining Functions, List Comprehensions.
0 PROGRAMMING IN HASKELL Some first steps Based on lecture notes by Graham Hutton The book “Learn You a Haskell for Great Good” (and a few other sources)
Computer Programming TCP1224 Chapter 4 Variables, Constants, and Arithmetic Operators.
Chapter 9: Functional Programming in a Typed Language.
Lee CSCE 314 TAMU 1 CSCE 314 Programming Languages Haskell: Types and Classes Dr. Hyunyoung Lee.
0 PROGRAMMING IN HASKELL Chapter 9 - Higher-Order Functions, Functional Parsers.
Overview of the Haskell 98 Programming Language
© M. Winter COSC 4P41 – Functional Programming Programming with actions Why is I/O an issue? I/O is a kind of side-effect. Example: Suppose there.
What is a Type? A type is a name for a collection of related values. For example, in Haskell the basic type Bool contains the two logical values: True.
0 Odds and Ends in Haskell: Folding, I/O, and Functors Adapted from material by Miran Lipovaca.
Lee CSCE 314 TAMU 1 CSCE 314 Programming Languages Interactive Programs: I/O and Monads Dr. Hyunyoung Lee.
0 PROGRAMMING IN HASKELL Chapter 4 - Defining Functions.
0 PROGRAMMING IN HASKELL Based on lecture notes by Graham Hutton The book “Learn You a Haskell for Great Good” (and a few other sources) Odds and Ends,
More Data Types CSCE 314 Spring CSCE 314 – Programming Studio Defining New Data Types Three ways to define types: 1.type – Define a synonym for.
Chapter 4: Variables, Constants, and Arithmetic Operators Introduction to Programming with C++ Fourth Edition.
An introduction to functional programming using Haskell CENG242 –Recitation 1.
1 PROGRAMMING IN HASKELL Lecture 2 Based on lecture notes by Graham Hutton The book “Learn You a Haskell for Great Good” (and a few other sources)
24-Jun-16 Haskell Dealing with impurity. Purity Haskell is a “pure” functional programming language Functions have no side effects Input/output is a side.
1 PROGRAMMING IN HASKELL Based on lecture notes by Graham Hutton The book “Learn You a Haskell for Great Good” (and a few other sources) Type declarations.
Set Comprehensions In mathematics, the comprehension notation can be used to construct new sets from old sets. {x2 | x  {1...5}} The set {1,4,9,16,25}
Set Comprehensions In mathematics, the comprehension notation can be used to construct new sets from old sets. {x2 | x  {1...5}} The set {1,4,9,16,25}
What is a Parser? A parser is a program that analyses a piece of text to determine its syntactic structure  3 means 23+4.
String is a synonym for the type [Char].
PROGRAMMING IN HASKELL
Types CSCE 314 Spring 2016.
Theory of Computation Lecture 4: Programs and Computable Functions II
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
A lightening tour in 45 minutes
PROGRAMMING IN HASKELL
Haskell.
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
Types and Classes in Haskell
PROGRAMMING IN HASKELL
CSCE 314: Programming Languages Dr. Dylan Shell
Haskell Types, Classes, and Functions, Currying, and Polymorphism
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
CSCE 314: Programming Languages Dr. Dylan Shell
PROGRAMMING IN HASKELL
Programming Languages
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
Theory of Computation Lecture 4: Programs and Computable Functions II
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
Presentation transcript:

0 PROGRAMMING IN HASKELL Chapter 11 - Interactive Programs, Declaring Types and Classes

Introduction 1 To date, we have seen how Haskell can be used to write batch programs that take all their inputs at the start and give all their outputs at the end. batch program inputsoutputs

2 However, we would also like to use Haskell to write interactive programs that read from the keyboard and write to the screen, as they are running. interactive program inputsoutputs keyboard screen

The Problem 3 Haskell programs are pure mathematical functions: However, reading from the keyboard and writing to the screen are side effects: zHaskell programs have no side effects. zInteractive programs have side effects.

The Solution 4 Interactive programs can be written in Haskell by using types to distinguish pure expressions from impure actions that may involve side effects. IO a The type of actions that return a value of type a.

5 For example: IO Char IO () The type of actions that return a character. The type of purely side effecting actions that return no result value. z() is the type of tuples with no components. Note:

Basic Actions 6 The standard library provides a number of actions, including the following three primitives: getChar :: IO Char zThe action getChar reads a character from the keyboard, echoes it to the screen, and returns the character as its result value:

7 zThe action putChar c writes the character c to the screen, and returns no result value: putChar :: Char  IO () zThe action return v simply returns the value v, without performing any interaction: return :: a  IO a

Sequencing 8 A sequence of actions can be combined as a single composite action using the keyword do. For example: a :: IO (Char,Char) a = do x  getChar getChar y  getChar return (x,y)

Derived Primitives 9 getLine :: IO String getLine = do x  getChar if x == '\n' then return [] else do xs  getLine return (x:xs) zReading a string from the keyboard:

10 putStr :: String  IO () putStr [] = return () putStr (x:xs) = do putChar x putStr xs zWriting a string to the screen: zWriting a string and moving to a new line: putStrLn :: String  IO () putStrLn xs = do putStr xs putChar '\n'

Example 11 We can now define an action that prompts for a string to be entered and displays its length: strlen :: IO () strlen = do putStr "Enter a string: " xs  getLine putStr "The string has " putStr (show (length xs)) putStrLn " characters"

12 For example: > strlen Enter a string: abcde The string has 5 characters zEvaluating an action executes its side effects, with the final result value being discarded. Note:

Hangman 13 Consider the following version of hangman: zOne player secretly types in a word. zThe other player tries to deduce the word, by entering a sequence of guesses. zFor each guess, the computer indicates which letters in the secret word occur in the guess.

14 zThe game ends when the guess is correct. hangman :: IO () hangman = do putStrLn "Think of a word: " word  sgetLine putStrLn "Try to guess it:" guess word We adopt a top down approach to implementing hangman in Haskell, starting as follows:

15 The action sgetLine reads a line of text from the keyboard, echoing each character as a dash: sgetLine :: IO String sgetLine = do x  getCh if x == '\n' then do putChar x return [] else do putChar '-' xs  sgetLine return (x:xs)

16 primitive getCh :: IO Char Note: zThe action getCh reads a character from the keyboard, without echoing it to the screen. zThis useful action is not part of the standard library, but is a special Hugs primitive that can be imported into a script as follows:

17 The function guess is the main loop, which requests and processes guesses until the game ends. guess :: String  IO () guess word = do putStr "> " xs  getLine if xs == word then putStrLn "You got it!" else do putStrLn (diff word xs) guess word

18 The function diff indicates which characters in one string occur in a second string: For example: > diff "haskell" "pascal" "-as--ll" diff :: String  String  String diff xs ys = [if elem x ys then x else '-' | x  xs]

Exercise 19 Implement the game of nim in Haskell, where the rules of the game are as follows: zThe board comprises five rows of stars: 1: * * * * * 2: * * * * 3: * * * 4: * * 5: *

20 zTwo players take it turn about to remove one or more stars from the end of a single row. zThe winner is the player who removes the last star or stars from the board. Hint: Represent the board as a list of five integers that give the number of stars remaining on each row. For example, the initial board is [5,4,3,2,1].

Type Declarations 21 In Haskell, a new name for an existing type can be defined using a type declaration. type String = [Char] String is a synonym for the type [Char].

22 Type declarations can be used to make other types easier to read. For example, given origin :: Pos origin = (0,0) left :: Pos  Pos left (x,y) = (x-1,y) type Pos = (Int,Int) we can define:

23 Like function definitions, type declarations can also have parameters. For example, given type Pair a = (a,a) we can define: mult :: Pair Int  Int mult (m,n) = m*n copy :: a  Pair a copy x = (x,x)

24 Type declarations can be nested: type Pos = (Int,Int) type Trans = Pos  Pos However, they cannot be recursive: type Tree = (Int,[Tree])

Data Declarations 25 A completely new type can be defined by specifying its values using a data declaration. data Bool = False | True Bool is a new type, with two new values False and True.

26 Note: zThe two values False and True are called the constructors for the type Bool. zType and constructor names must begin with an upper-case letter. zData declarations are similar to context free grammars. The former specifies the values of a type, the latter the sentences of a language.

27 answers :: [Answer] answers = [Yes,No,Unknown] flip :: Answer  Answer flip Yes = No flip No = Yes flip Unknown = Unknown data Answer = Yes | No | Unknown we can define: Values of new types can be used in the same ways as those of built in types. For example, given

28 The constructors in a data declaration can also have parameters. For example, given data Shape = Circle Float | Rect Float Float square :: Float  Shape square n = Rect n n area :: Shape  Float area (Circle r) = pi * r^2 area (Rect x y) = x * y we can define:

29 Note: zShape has values of the form Circle r where r is a float, and Rect x y where x and y are floats. zCircle and Rect can be viewed as functions that construct values of type Shape: Circle :: Float  Shape Rect :: Float  Float  Shape

30 Not surprisingly, data declarations themselves can also have parameters. For example, given data Maybe a = Nothing | Just a safediv :: Int  Int  Maybe Int safediv _ 0 = Nothing safediv m n = Just (m `div` n) safehead :: [a]  Maybe a safehead [] = Nothing safehead xs = Just (head xs) we can define:

Recursive Types 31 In Haskell, new types can be declared in terms of themselves. That is, types can be recursive. data Nat = Zero | Succ Nat Nat is a new type, with constructors Zero :: Nat and Succ :: Nat  Nat.

32 Note: zA value of type Nat is either Zero, or of the form Succ n where n :: Nat. That is, Nat contains the following infinite sequence of values: Zero Succ Zero Succ (Succ Zero)   

33 zWe can think of values of type Nat as natural numbers, where Zero represents 0, and Succ represents the successor function 1+. zFor example, the value Succ (Succ (Succ Zero)) represents the natural number 1 + (1 + (1 + 0))3 =

34 Using recursion, it is easy to define functions that convert between values of type Nat and Int: nat2int :: Nat  Int nat2int Zero = 0 nat2int (Succ n) = 1 + nat2int n int2nat :: Int  Nat int2nat 0 = Zero int2nat (n+1) = Succ (int2nat n)

35 Two naturals can be added by converting them to integers, adding, and then converting back: However, using recursion the function add can be defined without the need for conversions: add :: Nat  Nat  Nat add m n = int2nat (nat2int m + nat2int n) add Zero n = n add (Succ m) n = Succ (add m n)

36 For example: add (Succ (Succ Zero)) (Succ Zero) Succ (add (Succ Zero) (Succ Zero)) = Succ (Succ (add Zero (Succ Zero)) = Succ (Succ (Succ Zero)) = Note: zThe recursive definition for add corresponds to the laws 0+n = n and (1+m)+n = 1+(m+n).

Arithmetic Expressions 37 Consider a simple form of expressions built up from integers using addition and multiplication. 1 +  32

38 Using recursion, a suitable new type to represent such expressions can be declared by: For example, the expression on the previous slide would be represented as follows: data Expr = Val Int | Add Expr Expr | Mul Expr Expr Add (Val 1) (Mul (Val 2) (Val 3))

39 Using recursion, it is now easy to define functions that process expressions. For example: size :: Expr  Int size (Val n) = 1 size (Add x y) = size x + size y size (Mul x y) = size x + size y eval :: Expr  Int eval (Val n) = n eval (Add x y) = eval x + eval y eval (Mul x y) = eval x * eval y

40 Note: zThe three constructors have types: Val :: Int  Expr Add :: Expr  Expr  Expr Mul :: Expr  Expr  Expr zMany functions on expressions can be defined by replacing the constructors by other functions using a suitable fold function. For example: eval = fold id (+) (*)

Binary Trees 41 In computing, it is often useful to store data in a two-way branching structure or binary tree

42 Using recursion, a suitable new type to represent such binary trees can be declared by: For example, the tree on the previous slide would be represented as follows: data Tree = Leaf Int | Node Tree Int Tree Node (Node (Leaf 1) 3 (Leaf 4)) 5 (Node (Leaf 6) 7 (Leaf 9))

43 We can now define a function that decides if a given integer occurs in a binary tree: occurs :: Int  Tree  Bool occurs m (Leaf n) = m==n occurs m (Node l n r) = m==n || occurs m l || occurs m r But… in the worst case, when the integer does not occur, this function traverses the entire tree.

44 Now consider the function flatten that returns the list of all the integers contained in a tree: flatten :: Tree  [Int] flatten (Leaf n) = [n] flatten (Node l n r) = flatten l ++ [n] ++ flatten r A tree is a search tree if it flattens to a list that is ordered. Our example tree is a search tree, as it flattens to the ordered list [1,3,4,5,6,7,9].

45 Search trees have the important property that when trying to find a value in a tree we can always decide which of the two sub-trees it may occur in: This new definition is more efficient, because it only traverses one path down the tree. occurs m (Leaf n) = m==n occurs m (Node l n r) | m==n = True | m<n = occurs m l | m>n = occurs m r

Exercises 46 (1) Using recursion and the function add, define a function that multiplies two natural numbers. (2) Define a suitable function fold for expressions, and give a few examples of its use. (3) A binary tree is complete if the two sub-trees of every node are of equal size. Define a function that decides if a binary tree is complete.