Haskell Chapter 7.

Slides:



Advertisements
Similar presentations
Haskell Chapter 7. Topics  Defining data types  Exporting types  Type parameters  Derived instances  Type synonyms  Either  Type classes  Not.
Advertisements

Haskell Chapter 5, Part I. Topics  Higher Order Functions  map, filter  Infinite lists Get out a piece of paper… we’ll be doing lots of tracing.
0 PROGRAMMING IN HASKELL Chapter 10 - Declaring Types and Classes.
String is a synonym for the type [Char].
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.
Advanced Programming Handout 9 Qualified Types (SOE Chapter 12)
Introduction to ML - Part 2 Kenny Zhu. What is next? ML has a rich set of structured values Tuples: (17, true, “stuff”) Records: {name = “george”, age.
Chapter 12 Qualified Types. Motivation  What should the principal type of (+) be? Int -> Int -> Int-- too specific a -> a -> a-- too general  It seems.
Arrays. A problem with simple variables One variable holds one value –The value may change over time, but at any given time, a variable holds a single.
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.
5 BASIC CONCEPTS OF ANY PROGRAMMING LANGUAGE Let’s get started …
Lee CSCE 314 TAMU 1 CSCE 314 Programming Languages Haskell: Types and Classes Dr. Hyunyoung Lee.
1 Functional Programming Lecture 6 - Algebraic Data Types.
0 Functors in Haskell Adapted from material by Miran Lipovaca.
© M. Winter COSC 4P41 – Functional Programming Modules in Haskell Using modules to structure a large program has a number of advantages: Parts of.
0 Odds and Ends in Haskell: Folding, I/O, and Functors Adapted from material by Miran Lipovaca.
Working With Objects Tonga Institute of Higher Education.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
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.
Defining Classes Modules and ADTs CSCE 314 Spring 2016.
1 Objective Caml (Ocaml) Aaron Bloomfield CS 415 Fall 2005.
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.
Week 21 Introduction to Programming Ms. Knudtzon C Period Lecture 3.
Copyright © Texas Education Agency, Computer Programming Variables and Data Types.
CMSC201 Computer Science I for Majors Lecture 25 – Classes
Polymorphic Functions
String is a synonym for the type [Char].
4. Java language basics: Function
Types CSCE 314 Spring 2016.
Haskell Chapter 2.
Lecture 2:Data Types, Functional Patterns, Recursion, Polymorphism
CS-104 Final Exam Review Victor Norman.
C Programming Tutorial – Part I
Agenda Warmup AP Exam Review: Litvin A2
Variables and Arithmetic Operators in JavaScript
សាកលវិទ្យាល័យជាតិគ្រប់គ្រង National University of Management
Lecture 11 B Methods and Data Passing
PROGRAMMING IN HASKELL
Object Oriented Programming (OOP) LAB # 8
PROGRAMMING IN HASKELL
Computer Science 312 Haskell Lists 1.
Random Numbers In today’s lesson we will look at:
Week 6 Object-Oriented Programming (2): Polymorphism
Built-In (a.k.a. Native) Types in C++
PROGRAMMING IN HASKELL
Pointers C#, pointers can only be declared to hold the memory addresses of value types int i = 5; int *p; p = &i; *p = 10; // changes the value of i to.
CSE 341 Section 2 Winter 2018 Adapted from slides by Nick Mooney, Nicholas Shahan, Patrick Larson, and Dan Grossman.
Type & Typeclass Syntax in function
Types and Classes in Haskell
PROGRAMMING IN HASKELL
CSE 341 Section 2 Nick Mooney Spring 2017
Haskell Types, Classes, and Functions, Currying, and Polymorphism
Records and Type Classes
Class.
Defining New Data Types
Chap 2. Identifiers, Keywords, and Types
Contact
2011年 5月 2011年 6月 2011年 7月 2011年 8月 Sunday Monday Tuesday Wednesday
PROGRAMMING IN HASKELL
Object-Oriented Programming and class Design
PROGRAMMING IN HASKELL
Review Previously User-defined data types: records, variants
Chengyu Sun California State University, Los Angeles
Week 7 - Monday CS 121.
Object-Oriented Programming and class Design
Records and Type Classes
Presentation transcript:

Haskell Chapter 7

Topics Defining data types Not covered Exporting types Type parameters Derived instances Type synonyms Either Type classes Not covered record syntax recursive data structures subclassing parameterized types as instances of type classes Yes-No type class (emulate JavaScript-like behavior) Functor type class

Example: Define a data type data Bool = False | True data keyword indicates a new data type Bool is not new, just an example False and True are value constructors | is “or” – Bool can be False or True Type name and value constructors must start with capital letter Value constructors are actually functions that return a value of a data type

Shape example -- Circle parms coordinates and radius -- Rectangle parms upper left and lower right coordinates data Shape = Circle Float Float Float | Rectangle Float Float Float Float *Main> :t Circle Circle :: Float -> Float -> Float -> Shape *Main> :t Rectangle Rectangle :: Float -> Float -> Float -> Float -> Shape

Shape continued Notice the pattern match against constructor area :: Shape -> Float area (Circle _ _ r) = pi * r ^2 area (Rectangle x1 y1 x2 y2) = (abs $ x2 - x1) * (abs y2 - y1) Notice the pattern match against constructor *Main> let c = Circle 3 4 5 *Main> area c 78.53982 But we don’t know how to show a circle (yet) *Main> c <interactive>:15:1: No instance for (Show Shape) arising from a use of `print' Possible fix: add an instance declaration for (Show Shape) In a stmt of an interactive GHCi command: print it remember $ is function application

Updating shape to be displayed data Shape = Circle Float Float Float | Rectangle Float Float Float Float deriving (Show) *Main> let c = Circle 3 4 5 *Main> c Circle 3.0 4.0 5.0

Improving Shape with a Point data type data Point = Point Float Float deriving (Show) data Shape = Circle Point Float | Rectangle Point Point deriving (Show) area :: Shape -> Float area (Circle _ r) = pi * r ^2 area (Rectangle (Point x1 y1) (Point x2 y2)) = (abs $ x2 - x1) * (abs y2 - y1) *Main> area (Rectangle (Point 0 0) (Point 100 100)) 10000.0

Another method for Shapes nudge :: Shape -> Float -> Float -> Shape nudge (Circle (Point x y) r) dx dy = Circle (Point (x+dx) (y+dy)) r nudge (Rectangle (Point x1 y1) (Point x2 y2)) dx dy = Rectangle (Point (x1+dx) (y1+dy)) (Point (x2+dx) (y2+dy)) *Main> nudge (Circle (Point 34 34) 10) 5 10 Circle (Point 39.0 44.0) 10.0

Exporting shape module Shapes ( Point(..) , Shape(..) , area , nudge ) where Shape(..) exports all value constructors (in this case Circle and Rectangle). Makes it easy to add more shapes later (OCP) If just export Shape, not Shape(..), can’t pattern match (Programming Languages: support for encapsulation)

Type Constructors A value constructor takes some parameters, produces a new value e.g., Circle takes 2 values (Point and Float), returns a circle value A type constructor takes a type as a parameter, returns a new type* Maybe type constructor defined as: data Maybe a = Nothing | Just a Can’t have just Maybe… needs to be Maybe something *we’ve seen code that writes code… this is type code that creates a new type

Type Constructors and Strong Typing Why is this useful? Strong typing. In Java, null can match any Object type. public Point fn() { return null; } // null is Point public Rectangle fn() { return null; } // null is Rectangle public Object fn() { return null; } // null is Object In Haskell, must be more specific. If might be “null” then: playerAt :: a -> Position -> Maybe Player If definitely a Player returned then: playerAt :: a -> Position -> Player More on typing: https://en.wikipedia.org/wiki/Strong_and_weak_typing

Usage Due to type inference, often don’t pass parameters to type constructors explicitly If a value is Just ‘a’, Haskell infers type as Maybe Char Maybe Char = Nothing | Just ‘a’ *Main> Just 'a' Just 'a' *Main> :t Just 'a' Just 'a' :: Maybe Char *Main> :t 'a' 'a' :: Char *Main> Just 1 Just 1 *Main> :t Just 1 Just 1 :: Num a => Maybe a *Main> :t 1 1 :: Num a => a

Play with it *Main> Just "Haha" Just "Haha" *Main> Just 84 *Main> :t Just "Haha" Just "Haha" :: Maybe [Char] *Main> :t Just 84 Just 84 :: Num a => Maybe a *Main> :t Nothing Nothing :: Maybe a *Main> Just 10 :: Maybe Double Just 10.0

Type class \= Java class In Java, we use a class as a blueprint to create objects In Haskell, you use type classes to make a data type, then think about how it can act* We do this with deriving If types of all fields are part of a type class, then our new type can be part of that type class String and Int are both Eq String and Int are both Show data Person = Person { name :: String, age :: Int } deriving (Eq, Show) * as stated in chapter 2, type class has some similarities to Java interfaces (not exact, of course)

Example *Shapes> let frodo = Person {name = "Frodo Baggins", age = 43} *Shapes> let bilbo = Person {name = "Bilbo Baggins", age = 100} *Shapes> bilbo Person {name = "Bilbo Baggins", age = 100} *Shapes> bilbo == frodo False *Shapes> let imposter = Person {name = "Frodo Baggins", age = 43} *Shapes> frodo == imposter True

Enum example data Day = Monday | Tuesday | Wednesday | Thursday | Friday | Saturday | Sunday deriving (Eq, Show, Ord, Read, Bounded, Enum) *Chap7> Wednesday Wednesday *Chap7> show Wednesday "Wednesday" *Chap7> read "Saturday" :: Day Saturday *Chap7> Saturday == Sunday False *Chap7> Monday `compare` Wednesday LT *Chap7> Saturday > Friday True *Chap7> minBound :: Day Monday *Chap7> maxBound :: Day Sunday *Chap7> let weekend = [Friday .. Sunday] (note space before ..) *Chap7> weekend [Friday,Saturday,Sunday]

Type Synonyms [Char] and String are type synonyms type PhoneNumber = String type Name = String type PhoneBook = [(Name, PhoneNumber)] inPhoneBook :: Name -> PhoneNumber -> PhoneBook -> Bool inPhoneBook name pnumber pbook = (name, pnumber) `elem` pbook Not covered: parameterized type synonyms

Could be Either Use to encapsulate a value of one type or another Is defined as: data Either a b = Left a | Right b deriving (Eq, Ord, Read, Show) *Chap7> Right 20 Right 20 *Chap7> Left "Whoa" Left "Whoa" *Chap7> :t Right 'a' Right 'a' :: Either a Char *Chap7> :t Left True Left True :: Either Bool b

Either with try (not exam material) The try functions try :: Exception e => IO a -> IO (Either e a)Source Similar to catch, but returns an Either result which is (Right a) if no exception of type e was raised, or (Left ex) if an exception of type e was raised and its value is ex. If any other type of exception is raised then it will be propagated up to the next enclosing exception handler. try a = catch (Right `liftM` a) (return . Left) http://www.haskell.org/ghc/docs/6.12.2/html/libraries/base-4.2.0.1/Control-Exception.html#7

Usage Maybe can be used if function might return a result or fail Either can be used if there are multiple possible results You’ll explore this more in the homework

Type Classes 102 Type classes are sort of like interfaces: they define behavior Types that can behave that way are made instances (just means they can use the functions associated with that type class) class Eq a where (==) :: a -> a -> Bool (/=) :: a -> a -> Bool x == y = not (x /= y) x /= y = not (x == y) note the mutual recursion… only need to implement one!

Using a type class data TrafficLight = Red | Yellow | Green instance Eq TrafficLight where Red == Red = True Green == Green = True Yellow == Yellow = True _ == _ = False instance Show TrafficLight where show Red = "Red Light" show Green = "Green Light" show Yellow = "Yellow Light"

Using the Traffic Light *Chap7> Red Red Light *Chap7> Red == Red True *Chap7> Red == Green False *Chap7> Red `elem` [Red, Green, Yellow]