CSCE 314 Programming Languages

Similar documents
CSCE 314 Programming Languages

Haskell Types, Classes, and Functions, Currying, and Polymorphism

These notes are intended exclusively for the personal usage of the students of CS352 at Cal Poly Pomona. Any other usage is prohibited without

Programming in Haskell Aug-Nov 2015

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

Overloading, Type Classes, and Algebraic Datatypes

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

INTRODUCTION TO FUNCTIONAL PROGRAMMING

Chapter 15. Functional Programming. Topics. Currying. Currying: example. Currying: example. Reduction

COSE212: Programming Languages. Lecture 3 Functional Programming in OCaml

A general introduction to Functional Programming using Haskell

Haskell Making Our Own Types and Typeclasses

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

CS 457/557: Functional Languages

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

Shell CSCE 314 TAMU. Haskell Functions

Inductive Data Types

An introduction introduction to functional functional programming programming using usin Haskell

Algebraic Types. Chapter 14 of Thompson

CS 320: Concepts of Programming Languages

CS 320: Concepts of Programming Languages

CS 360: Programming Languages Lecture 12: More Haskell

IA014: Advanced Functional Programming

Informatics 1 Functional Programming Lecture 9. Algebraic Data Types. Don Sannella University of Edinburgh

CS 440: Programming Languages and Translators, Spring 2019 Mon

CSc 372. Comparative Programming Languages. 18 : Haskell Type Classes. Department of Computer Science University of Arizona

CS 320 Homework One Due 2/5 11:59pm

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

A Fourth Look At ML. Chapter Eleven Modern Programming Languages, 2nd ed. 1

Advanced features of Functional Programming (Haskell)

CSCE 314 Programming Languages. Functional Parsers

CS 457/557: Functional Languages

UNIVERSITY OF SWAZILAND SUPPLEMENTARY EXAMINATION, JULY 2013

Custom Types. Outline. COMP105 Lecture 19. Today Creating our own types The type keyword The data keyword Records

Introduction to Functional Programming in Haskell 1 / 56

C++: Const Function Overloading Constructors and Destructors Enumerations Assertions

Haskell Refresher Informatics 2D

Object-Oriented Principles and Practice / C++

Data Types The ML Type System

EECS 700 Functional Programming

Exploring Languages with Interpreters and Functional Programming Chapter 21

Abstract Types, Algebraic Types, and Type Classes

CSCE 314 Programming Languages

Shell CSCE 314 TAMU. Functions continued

CSCE 314 Programming Languages. Monadic Parsing

Type-indexed functions in Generic Haskell

Advances in Programming Languages

Note first midterm date: Wed. evening, Feb. 23 Today's class: Types in OCaml and abstract syntax

CSCE 314 Programming Languages. Monadic Parsing

Exercise 1 (2+2+2 points)

PROGRAMMING IN HASKELL. Chapter 2 - First Steps

Exercise 1 ( = 22 points)

Functional Programming Mid-term exam Tuesday 3/10/2017

CSCE 314 Programming Languages Functors, Applicatives, and Monads

The List Datatype. CSc 372. Comparative Programming Languages. 6 : Haskell Lists. Department of Computer Science University of Arizona

Haskell 101. (Version 1 (July 18, 2012)) Juan Pedro Villa Isaza

Exercise 1 ( = 24 points)

CSE 3302 Programming Languages Lecture 8: Functional Programming

Programming with Math and Logic

GADTs. Wouter Swierstra and Alejandro Serrano. Advanced functional programming - Lecture 7. [Faculty of Science Information and Computing Sciences]

Haskell An Introduction

COP4020 Programming Assignment 1 - Spring 2011

Haskell 98 in short! CPSC 449 Principles of Programming Languages

02157 Functional Programming Tagged values and Higher-order list functions

GADTs. Alejandro Serrano. AFP Summer School. [Faculty of Science Information and Computing Sciences]

List Functions, and Higher-Order Functions

Haskell Overloading (1) LiU-FP2016: Lecture 8 Type Classes. Haskell Overloading (3) Haskell Overloading (2)

CSC324 Principles of Programming Languages

Practical Haskell. An introduction to functional programming. July 21, Practical Haskell. Juan Pedro Villa-Isaza. Introduction.

Lecture 19: Functions, Types and Data Structures in Haskell

CS 360: Programming Languages Lecture 10: Introduction to Haskell

CMSC 330: Organization of Programming Languages

Typed Racket: Racket with Static Types

C# Fundamentals. Hans-Wolfgang Loidl School of Mathematical and Computer Sciences, Heriot-Watt University, Edinburgh

Programming Languages Fall 2013

Programming Language Concepts, CS2104 Lecture 7

Principles of Programming Languages 2017W, Functional Programming

Topic 7: Algebraic Data Types

Graphical Untyped Lambda Calculus Interactive Interpreter

BLM2031 Structured Programming. Zeyneb KURT

FUNCTIONAL PROGRAMMING NO.9 TYPE AND CLASS. Tatsuya Hagino

02157 Functional Programming. Michael R. Ha. Tagged values and Higher-order list functions. Michael R. Hansen

Solution sheet 1. Introduction. Exercise 1 - Types of values. Exercise 2 - Constructors

Programming Languages

Haskell Programs. Haskell Fundamentals. What are Types? Some Very Basic Types. Types are very important in Haskell:

Programming Languages

02157 Functional Programming. Michael R. Ha. Disjoint Unions and Higher-order list functions. Michael R. Hansen

Programming Paradigms

CS 381: Programming Language Fundamentals

Haskell 5.1 INTERACTIVE SESSIONS AND THE RUN-TIME SYSTEM

GADTs. Wouter Swierstra. Advanced functional programming - Lecture 7. Faculty of Science Information and Computing Sciences

12 CREATING NEW TYPES

Introduction Primitive Data Types Character String Types User-Defined Ordinal Types Array Types. Record Types. Pointer and Reference Types

FUNCTIONAL PROGRAMMING 1 HASKELL BASICS

Lecture 2: List algorithms using recursion and list comprehensions

Recap: ML s Holy Trinity

PROGRAMMING IN HASKELL. CS Chapter 6 - Recursive Functions

CIS552: Advanced Programming

CSE399: Advanced Programming. Handout 2

CSC324- TUTORIAL 5. Shems Saleh* *Some slides inspired by/based on Afsaneh Fazly s slides

Transcription:

CSCE 314 Programming Languages Haskell: Declaring Types and Classes Dr. Hyunyoung Lee 1

Outline Declaring Data Types Class and Instance Declarations 2

Defining New Types Three constructs for defining types: 1. data - Define a new algebraic data type from scratch, describing its constructors 2. type - Define a synonym for an existing type (like typedef in C) 3. newtype - A restricted form of data that is more efficient when it fits (if the type has exactly one constructor with exactly one field inside it). Used for defining wrapper types 3

Data Declarations 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. The two values False and True are called the constructors for the data type Bool. Type and constructor names must begin with an uppercase letter. Data declarations are similar to context free grammars. The former specifies the values of a type, the latter the sentences of a language. More examples from standard Prelude: data () = () -- unit datatype data Char = a b 4

Values of new types can be used in the same ways as those of built in types. For example, given we can define: data Answer = Yes No Unknown answers answers :: [Answer] = [Yes,No,Yes,Unknown] flip :: Answer -> Answer flip Yes = No flip No = Yes flip Unknown = Unknown Constructors construct values, or serve as patterns 5

Another example: data Weekday = Mon Tue Wed Thu Fri Sat Sun Constructors construct values, or serve as patterns next :: Weekday -> Weekday next Mon = Tue next Tue = Wed next Wed = Thu next Thu = Fri next Fri = Sat next Sat = Sun next Sun = Mon workday :: Weekday -> Bool workday Sat = False workday Sun = False workday _ = True 6

Constructors with Arguments The constructors in a data declaration can also have parameters. For example, given data Shape = Circle Float Rect Float Float we can define: square square n :: Float Shape = Rect n n area :: Shape Float area (Circle r) = pi * r^2 area (Rect x y) = x * y 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 7

Another example: data Person = Person Name Gender Age type Name = String data Gender = Male Female type Age = Int With just one constructor in a data type, often constructor is named the same as the type (cf. Person). Now we can do: let x = Person Jerry Female 12 y = Person Tom Male 12 in Quiz: What are the types of the constructors Male and Person? Male :: Gender Person :: Name -> Gender -> Age -> Person 8

Pattern Matching name (Person n ) = n oldman (Person _ Male a) a > 100 = True oldman (Person _) = False > let yoda = Person Yoda Male 999 in oldman yoda True findprsn n (p@(person m ):ps) n == m = p otherwise = findprsn n ps > findprsn Tom [Person Yoda Male 999, Person Tom Male 7] Person Tom Male 7 9

Parameterized Data Declarations Not surprisingly, data declarations themselves can also have parameters. For example, given we can define: x = Pair 1 2 y = Pair "Howdy" 42 data Pair a b = Pair a b first :: Pair a b -> a first (Pair x _) = x apply :: (a -> a )->(b -> b') -> Pair a b -> Pair a' b' apply f g (Pair x y) = Pair (f x) (g y) 10

Another example: Maybe type holds a value (of any type) or holds nothing 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) Lee CSCE 314 TAMU a is a type parameter, can be bound to any type Just True :: Maybe Bool Just x :: Maybe [Char] Nothing :: Maybe a 11

Type Declarations 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. For example, given type Pos = (Int,Int) we can define: origin :: Pos origin = (0,0) left :: Pos Pos left (x,y) = (x-1,y) 12

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 copy x :: a -> Pair a = (x,x) 13

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

Recursive Data Types New types can be declared in terms of themselves. That is, data types can be recursive. data Nat = Zero Succ Nat Nat is a new type, with constructors Zero :: Nat and Succ :: Nat -> Nat. 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: Example function: Zero Succ Zero Succ (Succ Zero)... add :: Nat -> Nat -> Nat add Zero n = n add (Succ m) n = Succ (add m n) 15

Parameterized Recursive Data Types - Lists data List a = Nil Cons a (List a) sum :: List Int -> Int sum Nil = 0 sum (Cons x xs) = x + sum xs > sum Nil 0 > sum (Cons 1 (Cons 2 (Cons 2 Nil))) 5 16

Trees A binary Tree is either Tnil, or a Node with a value of type a and two subtrees (of type Tree a) data Tree a = Tnil Node a (Tree a) (Tree a) Find an element: treeelem :: (a -> Bool) -> Tree a -> Maybe a treeelem p Tnil = Nothing treeelem p t@(node v left right) p v = Just v otherwise = treeelem p left `combine` treeelem p right where combine (Just v) r = Just v combine Nothing r = r Compute the depth: depth Tnil = 0 depth (Node _ left right) = 1 + (max (depth left) (depth right)) 17

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

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 1) (Mul (Val 2) (Val 3)) 19

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 20

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: fold :: (Int->Int)->(Int->Int->Int)-> (Int->Int->Int)->Expr->Int fold f g h (Val n) = f n fold f g h (Add a b) = g (fold f g h a) (fold f g h b) fold f g h (Mul a b) = h (fold f g h a) (fold f g h b) eval = fold id (+) (*) 21

About Folds A fold operation for Trees: treefold :: t -> (a -> t -> t -> t) -> Tree a -> t treefold f g Tnil = f treefold f g (Node x l r) = g x (treefold f g l) (treefold f g r) How? Replace all Tnil constructors with f, all Node constructors with g. Examples: > let tt = Node 1 (Node 2 Tnil Tnil) (Node 3 Tnil (Node 4 Tnil Tnil)) > treefold 1 (\x y z -> 1 + max y z) tt 4 > treefold 1 (\x y z -> x * y * z) tt 24 > treefold 0 (\x y z -> x + y + z) tt 10 22

Deriving Experimenting with the above definitions will give you many errors Data types come with no functionality by default, you cannot, e.g., compare for equality, print (show) values etc. Real definition of Bool data Bool = False True deriving (Eq, Ord, Enum, Read, Show, Bounded) A few standard type classes can be listed in a deriving clause Implementations for the necessary functions to make a data type an instance of those classes are generated by the compiler deriving can be considered a shortcut, we will discuss the general mechanism later 23

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

Outline Declaring Data Types Class and Instance Declarations 25

Type Classes A new class can be declared using the class construct Type classes are classes of types, thus not types themselves Example: class Eq a where (==), (/=) :: a -> a -> Bool -- Minimal complete definition: (==) and (/=) x /= y = not (x == y) x == y = not (x /= y) For a type a to be an instance of the class Eq, it must support equality and inequality operators of the specified types Definitions are given in an instance declaration A class can specify default definitions 26

Instance Declarations class Eq a where (==), (/=) :: a -> a -> Bool x /= y = not (x == y) x == y = not (x /= y) Let us make Bool be a member of Eq instance Eq Bool where (==) False False = True (==) True True = True (==) = False Due to the default definition, (/=) need not be defined deriving Eq would generate an equivalent definition 27

Showable Weekdays class Show a where showsprec :: Int -> a -> ShowS - to control parenthesizing show :: a -> String showsprec _ x s = show x ++ s show x = showsprec 0 x showsprec can improve efficiency: (((as ++ bs) ++ cs) ++ ds) vs. (as ++). (bs ++). (cs ++). (ds ++) Option 1: data Weekday = Mon Tue Wed Thu Fri Sat Sun deriving Show > map show [Mon, Tue, Wed] [ Mon, Tue, Wed ] 28

Showable Weekdays Option 2: data Weekday = Mon Tue Wed Thu Fri Sat Sun instance Show Weekday where show Mon = Monday show Tue = Tuesday... > map show [Mon, Tue, Wed] [ Monday, Tuesday, Wednesday ] 29

Parameterized Instance Declarations Every list is showable if its elements are instance Show a => Show [a] where show [] = [] show (x:xs) = [ ++ show x ++ showrest xs where showrest [] = ] showrest (x:xs) =, ++ show x ++ showrest xs Now this works: > show [Mon, Tue, Wed] [Monday,Tuesday,Wednesday] 30

Showable, Readable, and Comparable Weekdays Lee CSCE 314 TAMU data Weekday = Mon Tue Wed Thu Fri Sat Sun deriving (Show, Read, Eq, Ord, Bounded, Enum) *Main> show Wed "Wed *Main> read "Fri" :: Weekday Fri *Main> Sat == Sun False *Main> Sat == Sat True *Main> Mon < Tue True *Main> Tue < Tue False *Main> Wed `compare` Thu LT 31

Bounded and Enumerable Weekdays data Weekday = Mon Tue Wed Thu Fri Sat Sun deriving (Show, Read, Eq, Ord, Bounded, Enum) *Main> minbound :: Weekday Mon *Main> maxbound :: Weekday Sun *Main> succ Mon Tue *Main> pred Fri Thu *Main> [Fri.. Sun] [Fri,Sat,Sun] *Main> [minbound.. maxbound] :: [Weekday] [Mon,Tue,Wed,Thu,Fri,Sat,Sun] 32