String is a synonym for the type [Char].

Slides:



Advertisements
Similar presentations
Modern Programming Languages, 2nd ed.
Advertisements

ML Datatypes.1 Standard ML Data types. ML Datatypes.2 Concrete Datatypes  The datatype declaration creates new types  These are concrete data types,
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.
Getting started with ML ML is a functional programming language. ML is statically typed: The types of literals, values, expressions and functions in a.
0 PROGRAMMING IN HASKELL Chapter 10 - Declaring Types and Classes.
ML: a quasi-functional language with strong typing Conventional syntax: - val x = 5; (*user input *) val x = 5: int (*system response*) - fun len lis =
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.
Using Types Slides thanks to Mark Jones. 2 Expressions Have Types: The type of an expression tells you what kind of value you might expect to see if you.
0 PROGRAMMING IN HASKELL Chapter 5 - List Comprehensions.
Cse536 Functional Programming 1 6/12/2015 Lecture #7, Oct. 18, 2004 Today’s Topics – Trees – Kinds of trees - branching factor –functions over trees –patterns.
0 PROGRAMMING IN HASKELL Chapter 4 - Defining Functions.
Advanced Programming Handout 9 Qualified Types (SOE Chapter 12)
0 PROGRAMMING IN HASKELL Chapter 11 - The Countdown Problem.
Chapter 5 Polymorphic and Higher-Order Functions.
0 PROGRAMMING IN HASKELL Chapter 3 - Types and Classes.
Chapter 12 Qualified Types. Motivation  What should the principal type of (+) be? Int -> Int -> Int-- too specific a -> a -> a-- too general  It seems.
Using Types Slides thanks to Mark Jones. 2 Expressions Have Types: The type of an expression tells you what kind of value you might expect to see if you.
0 PROGRAMMING IN HASKELL Typeclasses and higher order functions Based on lecture notes by Graham Hutton The book “Learn You a Haskell for Great Good” (and.
0 PROGRAMMING IN HASKELL Chapter 11 - Interactive Programs, Declaring Types and Classes.
Tuples and Lists Lecture 3, Programmeringsteknik del A.
PrasadCS7761 Haskell Data Types/ADT/Modules Type/Class Hierarchy Lazy Functional Language.
S EARCHING AND T REES COMP1927 Computing 15s1 Sedgewick Chapters 5, 12.
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.
Syntax Analysis The recognition problem: given a grammar G and a string w, is w  L(G)? The parsing problem: if G is a grammar and w  L(G), how can w.
0 REVIEW OF HASKELL A lightening tour in 45 minutes.
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.
© 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.
1 Compiler Construction (CS-636) Muhammad Bilal Bashir UIIT, Rawalpindi.
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.
Haskell Chapter 5, Part II. Topics  Review/More Higher Order Functions  Lambda functions  Folds.
 Most C programs perform calculations using the C arithmetic operators (Fig. 2.9).  Note the use of various special symbols not used in algebra.  The.
An introduction to functional programming using Haskell CENG242 –Recitation 1.
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.
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].
Conditional Expressions
PROGRAMMING IN HASKELL
Types CSCE 314 Spring 2016.
ML: a quasi-functional language with strong typing
A Simple Syntax-Directed Translator
PROGRAMMING IN HASKELL
A lightening tour in 45 minutes
PROGRAMMING IN HASKELL
Abstract Syntax Trees Lecture 14 Mon, Feb 28, 2005.
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
Lecture 7: Introduction to Parsing (Syntax Analysis)
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
PROGRAMMING IN HASKELL
CSCE 314: Programming Languages Dr. Dylan Shell
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
Trees Today’s Topics Trees Kinds of trees - branching factor
list data list 만들기 list 사용하기 nil : list link :  * list -> list
Presentation transcript:

PROGRAMMING IN HASKELL Chapter 10 - Declaring Types and Classes

String is a synonym for the type [Char]. Type Declarations 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].

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

Like function definitions, type declarations can also have parameters 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)

Type declarations can be nested: type Pos = (Int,Int) type Trans = Pos  Pos Trans is intended to represent a graphics translation: move by (x, y) However, they cannot be recursive: type Tree = (Int,[Tree])

Bool is a new type, with two new values False and True. Data Declarations A completely new type can be defined by specifying its values using a data declaration. Data declarations are tree structures with named nodes. A Data declaration creates one or more node names. We’ll see examples below. Until now, the only data structures we’ve had were built in: lists and tuples. data Bool = False | True Bool is a new type, with two new values False and True.

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

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

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

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

An attempt to be clever with error values. Not surprisingly, data declarations themselves can also have parameters. For example, given data Maybe a = Nothing | Just a we can define: 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) An attempt to be clever with error values.

Recursive Types In Haskell, new types can be declared in terms of themselves. That is, types can be recursive. It wouldn’t be a symbolic programming language course without the Natural numbers. data Nat = Zero | Succ Nat Nat is a new type, with constructors Zero :: Nat and Succ :: Nat  Nat.

Note: A 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 Zero Succ (Succ Zero) Succ (Succ (Succ Zero)) 

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

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)

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

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: The recursive definition for add corresponds to the laws 0+n = n and (1+m)+n = 1+(m+n).

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

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

The number of nodes in the tree. 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 The number of nodes in the tree.

The three constructors have types: Note: The three constructors have types: Val :: Int  Expr Add :: Expr  Expr  Expr Mul :: Expr  Expr  Expr Many 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 In computing, it is often useful to store data in a two-way branching structure or binary tree. 5 7 9 6 3 4 1

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

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.

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

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: 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 This new definition is more efficient, because it only traverses one path down the tree.

data Tree = Leaf Int | Node Tree Int Tree deriving (Show, Eq) foldTree doNode doLeaf (Node left i right) = doNode (foldTree doNode doLeaf left) i (foldTree doNode doLeaf right) foldTree doNode doLeaf (Leaf i) = doLeaf i Use the default Show and Eq. The function to apply when the argument is an internal node. The function to apply when the argument is a leaf node f = (Node (Node (Leaf 1) 3 (Leaf 4)) 5 (Node (Leaf 6) 7 (Leaf 9))) size = foldTree (\left i right -> left + right + 1) (\_ -> 1) postOrder = foldTree (\ls node rs -> ls ++ rs ++ [node]) (\n -> [n]) The node function. The leaf function. Main> f Node (Node (Leaf 1) 3 (Leaf 4)) 5 (Node (Leaf 6) 7 (Leaf 9)) Main> size f 7

data Tree = Leaf Int | Node Tree Int Tree deriving (Show,Eq) data Expr = Val Int | Add Expr Expr | Mul Expr Expr deriving (Show,Eq) foldExpr doVal doAdd doMul (Val i) = doVal i foldExpr doVal doAdd doMul (Add e1 e2) = doAdd (foldExpr doVal doAdd doMul e1) (foldExpr doVal doAdd doMul e2) foldExpr doVal doAdd doMul (Mul e1 e2) = doMul (foldExpr doVal doAdd doMul e1) -- eval = foldExpr (\a -> a) (\a b -> a + b) (\a b -> a * b) eval = foldExpr id (+) (*)

Exercises (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.