Modelling & Datatypes Koen Lindström Claessen. Software Software = Programs + Data.

Slides:



Advertisements
Similar presentations
Functional Programming Lecture 10 - type checking.
Advertisements

Modelling & Datatypes John Hughes. Software Software = Programs + Data.
Minibridge Cowbridge Comprehensive July 2007 Patrick Jourdain.
Modelling & Datatypes Koen Lindström Claessen. Software Software = Programs + Data.
Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view class.
Classes and Objects. What is Design? The parts of the software including – what information each part holds – what things each part can do – how the various.
F28PL1 Programming Languages Lecture 14: Standard ML 4.
Making Decisions in Python Sec 9-10 Web Design. Objectives The student will: Understand how to make a decision in Python Understand the structure of an.
ML: a quasi-functional language with strong typing Conventional syntax: - val x = 5; (*user input *) val x = 5: int (*system response*) - fun len lis =
NUMBER TRICKS.
Recursive Data Types Koen Lindström Claessen. Modelling Arithmetic Expressions Imagine a program to help school-children learn arithmetic, which presents.
12 Pontoon1May Pontoon program CE : Fundamental Programming Techniques.
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.
Datastructures Koen Lindström Claessen (guest lecture by Björn Bringert)
Test Data Generators Lecture 5. Why Distinguish Instructions? Functions always give the same result for the same arguments Instructions can behave differently.
Selection Statements choice of one among several blocks of code Java supports 3 kinds of selection statements: if statement – selects one block or leaves.
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 5 Section 5 Permutations and Combinations.
Chapter 5 Black Jack. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. 5-2 Chapter Objectives Provide a case study example from problem statement.
Type Inference: CIS Seminar, 11/3/2009 Type inference: Inside the Type Checker. A presentation by: Daniel Tuck.
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.
VOCABULARY  Deck or pack  Suit  Hearts  Clubs  Diamonds  Spades  Dealer  Shuffle  Pick up  Rank  Draw  Set  Joker  Jack 
Induction and recursion
Refreshing Your Skills for Chapter 10.  If you flip a coin, the probability that it lands with heads up is 1/2.  If you roll a standard die, the probability.
Combinations Problems Problem 1: Sometimes we can use several counting techniques in the same problem, such as combinations and the addition principle.
Pattern matching. The if expression The else part of an if expression is optional if ( condition ) expression1 else expression2 If the condition evaluates.
COSC 2006 Data Structures I Recursion II
Copyright 2013, 2010, 2007, Pearson, Education, Inc. Section 12.2 Theoretical Probability
A Singleton Puzzle: What is Printed? 1 public class Elvis { public static final Elvis INSTANCE = new Elvis(); private final int beltSize; private static.
Chapter  Determine how many different possibilities are possible:  1. There are 3 different ice cream flavors and 5 different toppings. You.
Flow of Control Part 1: Selection
Introduction to Computer Science 2 Slide 1 Enumerated types We already know some data types int, float, char good for problems that involve int,
1 Functional Programming Lecture 6 - Algebraic Data Types.
Backtracking and Games Eric Roberts CS 106B January 28, 2013.
HAWKES LEARNING Students Count. Success Matters. Copyright © 2015 by Hawkes Learning/Quant Systems, Inc. All rights reserved. Section 2.3 Operations with.
1 CS 457/557: Functional Languages Lists and Algebraic Datatypes Mark P Jones Portland State University.
Objects and Classes Continued Engineering 1D04, Teaching Session 10.
Function Definition by Cases and Recursion Lecture 2, Programmeringsteknik del A.
Draw 3 cards without replacement from a standard 52 card deck. What is the probability that: 1.They are all red ? 2.At least one is black ? 3.They are.
1 Lecture 2 Control Structures: Part 1 Selection: else / if and switch.
Chapter 8: Arrays Gator Engineering One-dimensional array Copyright © 2008 W. W. Norton & Company. All rights reserved. 1 Move the first element to the.
Midterm Review Tami Meredith. Primitive Data Types byte, short, int, long Values without a decimal point,..., -1, 0, 1, 2,... float, double Values with.
Chance We will base on the frequency theory to study chances (or probability).
Introduction to Enumerations CMSC 202. Enumerated Values Enumerated values are used to represent a set of named values. Historically in Java (and other.
Some Practical Information + Programming with Lists Sept Koen Lindström Claessen.
Arrangements and Selections (and how they may be counted)
Test Data Generators. Why Distinguish Instructions? Functions always give the same result for the same arguments Instructions can behave differently on.
Some Practical Information + Programming with Lists
Types CSCE 314 Spring 2016.
Koen Lindström Claessen
Combinations Problems
Koen Lindström Claessen
Haskell Chapter 2.
Class 11: Two-argument recursion
BEGINNERS’ LESSONS Welcome
The Addition Rule.
Chapter 5 Black Jack.
Section 2 – CSE341 Patrick Larson, Spring 2013.
Test Data Generators.
Koen Lindström Claessen
Section 2 – CSE341 Konstantin Weitz.
Nicholas Shahan Spring 2016
CSE 341 Section 2 Winter 2018 Adapted from slides by Nick Mooney, Nicholas Shahan, Patrick Larson, and Dan Grossman.
Computational Thinking for KS3
CSE 341 PL Section 2 Justin Harjanto.
Type & Typeclass Syntax in function
Spencer Pearson Spring 2017
CSE 341 Section 2 Nick Mooney Spring 2017
PROGRAMMING IN HASKELL
Presentation transcript:

Modelling & Datatypes Koen Lindström Claessen

Software Software = Programs + Data

Modelling Data A big part of designing software is modelling the data in an appropriate way Numbers are not good for this! We model the data by defining new types

Modelling a Card Game Every card has a suit Model by a new type: data Suit = Spades | Hearts | Diamonds | Clubs The new type The values of this type Hearts, Whist, Plump, Bridge,...

Investigating the new type Main> :i Suit -- type constructor data Suit -- constructors: Spades :: Suit Hearts :: Suit Diamonds :: Suit Clubs :: Suit Main> :i Spades Spades :: Suit -- data constructor The new type The new values -- constructors Types and constructors start with a capital letter

Printing Values Fix Main> Spades ERROR - Cannot find "show" function for: *** Expression : Spades *** Of type : Suit Main> :i show show :: Show a => a -> String -- class member Needed to print values data Suit = Spades | Hearts | Diamonds | Clubs deriving Show Main> Spades Spades

The Colours of Cards Each suit has a colour – red or black Model colours by a type Define functions by pattern matching data Colour = Black | Red deriving Show colour :: Suit -> Colour colour Spades = Black colour Hearts = Red colour Diamonds = Red colour Clubs = Black One equation per value Main> colour Hearts Red

The Ranks of Cards Cards have ranks: 2..10, J, Q, K, A Model by a new type Numeric ranks data Rank = Numeric Integer | Jack | Queen | King | Ace deriving Show Main> :i Numeric Numeric :: Integer -> Rank -- data constructor Main> Numeric 3 Numeric 3 Numeric ranks contain an Integer

Rank Beats Rank When does one rank beat another? AKQJmAKQJm nJQKAnJQKA m>n

Rank Beats Rank rankBeats :: Rank -> Rank -> Bool

Rank Beats Rank When does one rank beat another? AKQJmAKQJm nJQKAnJQKA m>n

Rank Beats Rank rankBeats :: Rank -> Rank -> Bool

Rank Beats Rank When does one rank beat another? AKQJmAKQJm nJQKAnJQKA m>n

Rank Beats Rank rankBeats :: Rank -> Rank -> Bool

Rank Beats Rank When does one rank beat another? AKQJmAKQJm nJQKAnJQKA m>n

Rank Beats Rank rankBeats :: Rank -> Rank -> Bool rankBeats _ Ace = False Matches anything at all Nothing beats an Ace

Rank Beats Rank When does one rank beat another? AKQJmAKQJm nJQKAnJQKA m>n

Rank Beats Rank rankBeats :: Rank -> Rank -> Bool rankBeats _ Ace = False rankBeats Ace _ = True Used only if the first equation does not match. An Ace beats anything else

Rank Beats Rank When does one rank beat another? AKQJmAKQJm nJQKAnJQKA m>n

Rank Beats Rank rankBeats :: Rank -> Rank -> Bool rankBeats _ Ace = False rankBeats Ace _ = True rankBeats _ King = False rankBeats King _ = True

Rank Beats Rank When does one rank beat another? AKQJmAKQJm nJQKAnJQKA m>n

Rank Beats Rank rankBeats :: Rank -> Rank -> Bool rankBeats _ Ace = False rankBeats Ace _ = True rankBeats _ King = False rankBeats King _ = True rankBeats _ Queen = False rankBeats Queen _ = True rankBeats _ Jack = False rankBeats Jack _ = True

Rank Beats Rank When does one rank beat another? AKQJmAKQJm nJQKAnJQKA m>n

Rank Beats Rank rankBeats :: Rank -> Rank -> Bool rankBeats _ Ace = False rankBeats Ace _ = True rankBeats _ King = False rankBeats King _ = True rankBeats _ Queen = False rankBeats Queen _ = True rankBeats _ Jack = False rankBeats Jack _ = True rankBeats (Numeric m) (Numeric n) = m > n Match Numeric 7, for example Names the number in the rank

Examples Main> rankBeats Jack (Numeric 7) True Main> rankBeats (Numeric 10) Queen False

A Property Either a beats b or b beats a prop_rankBeats a b = rankBeats a b || rankBeats b a Main> quickCheck prop_rankBeats ERROR - Cannot infer instance *** Instance : Arbitrary Rank *** Expression : quickCheck prop_rankBeats QuickCheck doesn’t know how to choose an arbitrary Rank!

Generators Test data is chosen by a test data generator Writing generators we leave for the future

Testing the Property prop_rankBeats a b = rankBeats a b || rankBeats b a Main> quickCheck prop_rankBeats Falsifiable, after 9 tests: King prop_rankBeats a b = a/=b ==> rankBeats a b || rankBeats b a data Rank = Numeric Integer | Jack | Queen | King | Ace deriving (Show, Eq) Provided they’re not equal Define == for ranks

Modelling a Card A Card has both a Rank and a Suit Define functions to inspect both data Card = Card Rank Suit deriving Show rank :: Card -> Rank rank (Card r s) = r suit :: Card -> Suit suit (Card r s) = s

A Useful Abbreviation Define type and inspection functions together, as follows data Card = Card {rank :: Rank, suit :: Suit} deriving Show

When does one card beat another? When both cards have the same suit, and the rank is higher cardBeats :: Card -> Card -> Bool cardBeats c c' | suit c == suit c' = rankBeats (rank c) (rank c') | otherwise = False data Suit = Spades | Hearts | Diamonds | Clubs deriving (Show, Eq) can be written down simpler...

When does one card beat another? When both cards have the same suit, and the rank is higher cardBeats :: Card -> Card -> Bool cardBeats c c' = suit c == suit c’ && rankBeats (rank c) (rank c')

Testing cardBeats Test the same property for cards prop_cardBeats a b = cardBeats a b || cardBeats b a

Testing cardBeats Test the same property for cards Of course! In general, the card played first wins! Main> quickCheck prop_cardBeats Falsifiable, after 0 tests: Card{rank=Numeric 7,suit=Hearts} Card{rank=Numeric 6,suit=Clubs} property does not hold!

Modelling a Hand of Cards A hand may contain any number of cards from zero up! The solution is… recursion! data Hand = Cards Card … Card deriving Show We can’t use …!!!

Modelling a Hand of Cards A hand may contain any number of cards from zero up! –A hand may be empty –It may consist of a first card and the rest The rest is another hand of cards! data Hand = Empty | Add Card Hand deriving Show A recursive type! Solve the problem of modelling a hand with one fewer cards! very much like a list...

When can a hand beat a card? An empty hand beats nothing A non-empty hand can beat a card if the first card can, or the rest of the hand can! A recursive function! handBeats :: Hand -> Card -> Bool handBeats Empty card = False handBeats (Add c h) card = cardBeats c card || handBeats h card

Choose a card to play Given –Card to beat –The hand Beat the card if possible!

Strategy If the hand is only one card, play it If there is a choice, –Select the best card from the rest of the hand –Choose between it and the first card Principles –Follow suit if possible –Play lowest winning card if possible –Play lowest losing card otherwise

The Code -- chooseCard trump beat hand chooses a card from hand to -- play, when trump is the trump suit and beat is the card to -- be beaten chooseCard :: Card -> Hand -> Hand chooseCard beat (Add c Empty) = c chooseCard beat (Add c rest) | suit c==suit beat && suit c’/=suit beat = c | suit c/=suit beat && suit c’==suit beat = c’ | rankBeats (rank c) (rank c’) = c’ | otherwise = c where c’ = chooseCard trump beat rest

Properties of chooseCard Complicated code with great potential for errors! Possible properties: –chooseCard returns a card from the hand (”no cards up the sleeve”) –chooseCard follows suit if possible (”no cheating”) –chooseCard always wins if possible

Testing chooseCard prop_chooseCardWinsIfPossible c h = h/=Empty ==> handBeats h c == cardBeats (chooseCard c h) c Main> quickCheck prop_chooseCardWinsIfPossible Falsifiable, after 3 tests: Card{rank=Numeric 8,suit=Diamonds} Add Card{rank=Numeric 4,suit=Diamonds} (Add Card{rank=Numeric 10,suit=Spades} Empty) What went wrong?

What Did We Learn? Modelling the problem using datatypes with components Using recursive datatypes to model things of varying size Using recursive functions to manipulate recursive datatypes Writing properties of more complex algorithms

Reminder: Modelling a Hand A Hand is either: –An empty hand –Formed by adding a card to a smaller hand Discarding the first card: data Hand = Empty | Add Card Hand deriving Show discard :: Hand -> Hand discard (Add c h) = h

Lists -- how they work

Lists A list is either: –An empty list –Formed by adding an element to a smaller list What to put on the place of the ?? data List = Empty | Add ?? List

Lists A type parameter Add 12 (Add 3 Empty) :: List Integer Add ”apa” (Add ”bepa” Empty) :: List String data List a = Empty | Add a (List a)

Lists Empty :: List Integer Empty :: List Bool Empty :: List String... data List a = Empty | Add a (List a)

Lists Can represent 0, 1, 2, … things –[], [3], [”apa”,”katt”,”val”,”hund”] They all have the same type –[1,3,True,”apa”] is not allowed The order matters –[1,2,3] /= [3,1,2] Syntax –5 : (6 : (3 : [])) == 5 : 6 : 3 : [] == [5,6,3] –”apa” == [’a’,’p’,’a’]

More on Types Functions can have ”general” types: –polymorphism –reverse :: [a] -> [a] –(++) :: [a] -> [a] -> [a] Sometimes, these types can be restricted –Ord a => … for comparisons (, >=, …) –Eq a => … for equality (==, /=) –Num a => … for numeric operations (+, -, *, …)

Do’s and Don’ts isBig :: Integer -> Bool isBig n | n > 9999 = True | otherwise = False isBig :: Integer -> Bool isBig n = n > 9999 guards and boolean results

Do’s and Don’ts resultIsSmall :: Integer -> Bool resultIsSmall n = isSmall (f n) == True resultIsSmall :: Integer -> Bool resultIsSmall n = isSmall (f n) comparison with a boolean constant

Do’s and Don’ts resultIsBig :: Integer -> Bool resultIsBig n = isSmall (f n) == False resultIsBig :: Integer -> Bool resultIsBig n = not (isSmall (f n)) comparison with a boolean constant

Writing Code Beautiful code –readable –not overly complicated –no repetitions –no ”junk” left For –you –other people