34
Lecture 3A Data Types: Basic types, Tuples, Polymorphism, Functions (incl. curried) COMP 1100

Lecture 3A Data Types: Basic types, Tuples, Polymorphism

  • Upload
    others

  • View
    13

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Lecture 3A Data Types: Basic types, Tuples, Polymorphism

Lecture 3AData Types: Basic types, Tuples, Polymorphism,

Functions (incl. curried)COMP 1100

Page 2: Lecture 3A Data Types: Basic types, Tuples, Polymorphism

Acknowledgement of Countryü I wish to acknowledge the traditional custodians of the land we

are meeting on, the Ngunnawal people. I wish to acknowledge and respect their continuing culture and the contribution they make to the life of this city and this region. I would also like to acknowledge and welcome any other Aboriginal and Torres Strait Islander people who are enrolled in our courses.

2

Page 3: Lecture 3A Data Types: Basic types, Tuples, Polymorphism

Representativesü u7074610 - VongVuthik Kolü u7074608 - Ziyi Yuü u7079217 - Mohit Goyalü u7145384 - Abhaas Goyalü u7199021 - Theodore Darmawan

3

Page 4: Lecture 3A Data Types: Basic types, Tuples, Polymorphism

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 False and True,ü The type Bool-> Bool contains all functions that map arguments from

Bool to Bool.ü Notation: v :: T means that v is a value in the type T, i.e. v has type T.ü Example

ü The symbol :: can be used as e :: T that evaluates the expression e and produce a value of type T.

ü Example

4

False :: BoolTrue :: Boolnot :: Bool -> Bool

not False :: Boolnot True :: Boolnot (not False) :: Bool

Page 5: Lecture 3A Data Types: Basic types, Tuples, Polymorphism

Type errorsü Applying a function to one or more arguments of the wrong type is called a

type error.

ü 1 is a number and False is a logical value, but + requires two numbers.

5

> 1 + Falseerror ...

Page 6: Lecture 3A Data Types: Basic types, Tuples, Polymorphism

What is a type?ü Every expression has a type!ü Typing rule

ü Example: then typing not False :: Bool

can be inferred from this rule using the fact thatnot :: Bool -> Bool and False :: Bool.

ü Example: the expression not 3 does not have a type, because this would require 3::Bool.

ü Because type inference precedes evaluation, Haskell programs are type safe.

6

f :: A -> B e :: Af e :: B

Page 7: Lecture 3A Data Types: Basic types, Tuples, Polymorphism

Six basic typesü Haskell has a number of basic types, including:1. Bool – logical values2. Char – single character

ü String – strings of characters

7

'H' ::Char

type String = [Char]"Hello world" :: String

Page 8: Lecture 3A Data Types: Basic types, Tuples, Polymorphism

Basic types3. Int – fixed-precision integers: −2!" to 2!" − 1

ü CPUs have built-in types, so it’s fast

8

2^63 - 1 :: Int9223372036854775807

2^63 :: Int-9223372036854775808

Most significant bit, 0 for + and 1 for -

Int 64 bits

0 à 00002

1 à 00012

2 à 00102

3 à 00112

4 à 01002

5 à 01012

6 à 011027 à 011128 à 10002

9 à 10012

10 à 10102

11 à 10112

12 à 11002

13 à 11012

14 à 11102

15 à 11112

01

2

3

4

56

7-8-7

-6

-5

-4

-3-2

-1

Singed

Unsignedü Example: N = 4

Page 9: Lecture 3A Data Types: Basic types, Tuples, Polymorphism

Basic types4. Integer – arbitrary-precision integers

ü Arbitrary precision integers are processed using the slower medium of software.

9

2^63 - 1 :: Integer9223372036854775807

2^63 :: Integer9223372036854775808

Page 10: Lecture 3A Data Types: Basic types, Tuples, Polymorphism

Basic types

5. Float – single-precision floating-point numbers6. Double– double precision floating-point numbers

10

sqrt (20000000)^2 :: Float1.9999998e7sqrt (20000000)^2 :: Double2.0e7

ü The IEEE 754 standard specifies a binary32 and binary64ü The numerical form as having: 𝑣𝑎𝑙𝑢𝑒 = −1 𝒔× 1.𝒎 $×2𝒆

ü s is a sign bit, determines whether number is negative or positiveü m is a significand, determines a fractional values in [1.0, 2.0 − 𝜖)ü e is a exponent which weights value by power of 2

exponent 𝐞∗sign: 𝐬 base: 𝐦…Float

1 8-bits 23-bits

…Double1 11-bits 53-bits

Page 11: Lecture 3A Data Types: Basic types, Tuples, Polymorphism

Basic typesü What is the type of the expression 7? Is

it Int, Integer, Float, or Double?ü Polymorphic type expressions essentially

describe families of types.

11

> :t 77 :: Num p => p

> :t 7.07.0 :: Fractional p => p

Arbitrary-precision fractions,Extracting components of fractions.

Integral numbers, supporting integer division.

Efficient, machine-independent access to the components of a floating-point number.

Page 12: Lecture 3A Data Types: Basic types, Tuples, Polymorphism

List typesü A list is sequence of values of the same type:

ü In general:[t] is the type of lists with elements of type t.

ü The number of elements is a list is called its length.ü The list [] is the empty list.ü Such lists as [False], [’a’], [[]] are called singletons.

12

[False,True,False] :: [Bool]

[’a’,’b’,’c’,’d’] :: [Char]

["One", "Two", "Three"] :: [String]

The empty list as its only element

Page 13: Lecture 3A Data Types: Basic types, Tuples, Polymorphism

List typesü Important points

ü The type of a list convey no information about its length

ü No restrictions on the type of the elements of a list

ü No restrictions that a list must have a finite length.

13

> :t [False, True][False, True] :: [Bool]

> :t [False, True, False][False, True, False] :: [Bool]

> [['a', 'b'], ['c', 'd', 'e']] :: [[Char]]["ab","cde"]

Page 14: Lecture 3A Data Types: Basic types, Tuples, Polymorphism

Tuple typeü A tuple is a finite sequence of components of possible different types

𝑖th components have type Ti, in the range 1 to n.ü Examples:

ü The number of components in a tuple is called its arity.ü The tuple () of arity zero is called the empty tuple.ü Tuple of arity one, such as (False) are not permitted

14

(T1, T2,..., Tn)

(False, True) :: (Bool, Bool)(False, 'a', True) :: (Bool, Char, Bool)("Yes", True, 'a') :: (String, Bool, Char)

Page 15: Lecture 3A Data Types: Basic types, Tuples, Polymorphism

Tuple typeü Important points

ü The type of a tuple conveys its arityü Example: (Bool, Char) contains all pairs produced the by Cartesian product

ü No restrictions on the types of the componentsü Example:

ü Tuples must have a finite arity.

15

('a', (False, 'b')) :: (Char, (Bool, Char))(['a', 'b'], [False, True]) :: ([Char], [Bool])[('a', False), ('b', True)] :: [(Char, Bool)]

Page 16: Lecture 3A Data Types: Basic types, Tuples, Polymorphism

Function typesü A function is a mapping from arguments of one type to results of another

type.

ü QUIZ: If 𝑇1 and 𝑇2 are of type Bool, how many different functions can be constructed ?

ü Example:

ü Function can be undefined for some arguments

16

𝑇1 𝑇2

𝑓 ∷ 𝑇1 → 𝑇2

add :: (Int, Int) -> Intadd (x, y) = x + y

zerto :: Int -> [Int]zerto n = [0..n]

> head []*** Exception: Prelude.head: empty list

Page 17: Lecture 3A Data Types: Basic types, Tuples, Polymorphism

Example: Tuples and functionsü The point of intersection of two non-parallel lines can be found from the

equations of the two lines.𝑎𝑥 + 𝑏𝑦 = 𝑚𝑐𝑥 + 𝑑𝑦 = 𝑛

ü The set has a unique solution

𝑥& =𝑚𝑑 − 𝑏𝑛𝑎𝑑 − 𝑐𝑏

𝑦& =𝑛𝑎 −𝑚𝑐𝑎𝑑 − 𝑐𝑏

17

intersection :: ((Double, Double, Double), (Double, Double, Double)) -> (Double, Double)

intersection ((a, b, m), (c, d, n)) = ((m*d - b*n)/(a*d - c*b), (n*a - m*c)/(a*d - c*b))

> intersection((1,2,3), (4,5,6))(-1.0,2.0)

Page 18: Lecture 3A Data Types: Basic types, Tuples, Polymorphism

Curried functionsü Functions in Haskell are free to return functions as results

add' is a function that takes an argument of type Int, and returns a result that is function of type Int -> Int.ü Important point: add’ takers an integer x and returns a function, that in

turn takes an integer y and returns the result x + y.

18

add' :: Int -> (Int -> Int)add' x y = x + y

add :: (Int, Int) -> Int -- returns a numberadd' :: Int -> (Int -> Int) -- returns a function

Page 19: Lecture 3A Data Types: Basic types, Tuples, Polymorphism

Curried functionsü Function with more arguments

ü ConventionsInt -> (Int -> (Int -> Int)) equivalent to Int -> Int -> Int -> Int

((mult x) y) z equivalent to mult x y z

19

mult :: Int -> (Int -> (Int -> Int))mult x y z = x*y*z

> mult 2 3 424> mult2 = mult 2> mult2 3 424> mult3 = mult2 3> mult3 424

Page 20: Lecture 3A Data Types: Basic types, Tuples, Polymorphism

QUIZ: tuples and curried functionsü Modify and test the function intersection so that it can take one

argument at a time.

20

intersection :: ((Double, Double, Double), (Double, Double, Double)) -> (Double, Double)

intersection ((a, b, m), (c, d, n)) = ((m*d - b*n)/(a*d - c*b), (n*a - m*c)/(a*d - c*b))

intersection :: (Double, Double, Double) -> (Double, Double, Double)-> (Double, Double)

intersection (a, b, m) (c, d, n) = ((m*d - b*n)/(a*d - c*b), (n*a-m*c)/(a*d - c*b)

)

> intersection2 = intersection (1,2,3)> intersection2 (4,5,6)(-1.0,2.0)

Page 21: Lecture 3A Data Types: Basic types, Tuples, Polymorphism

Polymorphic typesü The library function length calculates the length of any list, irrespective of

the type of the elements of the list:

ü The type of length is as follows

For any type a, the function length has type [a] -> Int.

21

> length [1, 3, 5, 7]4> length ["Yes", "No"]2> length [sin, cos, tan]3

length :: [a] -> Int

Page 22: Lecture 3A Data Types: Basic types, Tuples, Polymorphism

Polymorphic typesü Examples: Standard prelude functions

ü The type indicates function’s behavior e.g. zip pairs up elements from two lists.

22

fst :: (a, b) -> ahead :: [a] -> atake :: Int -> [a] -> [a]zip :: Int -> [a] -> [b] -> [(a, b)]id :: a -> a

Page 23: Lecture 3A Data Types: Basic types, Tuples, Polymorphism

Overloaded typesü Class constraint are written in the form

C awhere C is the name of a class and a is a type variable.ü Example:

ü A type that contains one or more class constrains is called overload.ü Most of the numeric functions in the prelude are overloaded

ü Numbers themselves are overloaded

23

(+) :: Num a => a -> a -> a

overloadan overloaded fn.

(*) :: Num a => a -> a -> anegate :: Num a => a -> aabs :: Num a=> a -> a

3 :: Num a => a

Page 24: Lecture 3A Data Types: Basic types, Tuples, Polymorphism

Basic classesü A type is a collection of related values.ü A class is a collection of types that support certain overloaded operation

called methods.ü The commonly used built-in classes are

ü Eq – equality typesü Ord – ordered typesü Show – showable typesü Read – readable typesü Num – numeric typesü Integral – integral typesü Fractional – fractional types

24

Page 25: Lecture 3A Data Types: Basic types, Tuples, Polymorphism

Basic classes: Showü This class contains type whose values can be converted into strings of

characters using the following method:

ü All basic types Bool, Char, String, Int, Integer, Float, and Double are instance of the Eq class, as are lists and tuple types.

ü Example

25

show :: a -> String

> show False"False"> show 'a'"'a'"> show 123"123"> show [1, 2, 3]"[1,2,3]"> show ('a', False)"('a',False)"

Page 26: Lecture 3A Data Types: Basic types, Tuples, Polymorphism

Basic classes: Readü Contains types whose values can be converted from strings of characters

ü All basic types Bool, Char, String, Int, Integer, Float, and Double are instance of the Eq class, as are lists and tuple types.

ü Example

ü The use of :: resolve the type of the result.ü In practice, the necessary type can be usually inferred automatically

26

read :: String -> a

> read "False" :: BoolFalse> read "'a'" :: Char'a'> read "123" :: Int123> read "[1, 2, 3]" :: [Int][1,2,3]> read "('a', False)" :: (Char, Bool)('a’, False)

> not (read "False")True

Page 27: Lecture 3A Data Types: Basic types, Tuples, Polymorphism

Appendix: Basic Data Types:Floating point representation

ü The IEEE 754 standard specifies a binary32 and binary64ü The numerical form as having:

𝑣𝑎𝑙𝑢𝑒 = −1 𝒔× 1.𝒎 $×2𝒆

ü s is a sign bit, determines whether number is negative or positiveü m is a significand, determines a fractional values in [1.0, 2.0 - 𝜖)ü e is a exponent which weights value by power of 2

27

exponent 𝐞∗sign: 𝐬 base: 𝐦…Float

1 8-bits 23-bits

…Double1 11-bits 53-bits

Page 28: Lecture 3A Data Types: Basic types, Tuples, Polymorphism

28

The exponent is in excess-127 binary notation• 11111111, reserved for special cases i.e. inf or nan• 00000000, reserved to represent zero• 01111111 = 127 represents an exponent of 0, • 10000000 = 128, represents +1, • 01111110 = 126 represents -1, • 11111110 = 254, represents +127• 00000001 = 1, represents -126 and so forth

𝑣𝑎𝑙𝑢𝑒 = −1 "!"× 1. 𝑏##𝑏#$…𝑏% #×2 "!#"$%…"$! $'$#(

b0b31

exponent 𝐞∗sign: 𝒔 base: 𝒎

ü The IEEE 754 standard specifies a binary32 (Float in Haskell) as having:ü Sign bit: 1 bitü Exponent width: 8 bitsü Significand (mantissa) precision: 24 bits (23 explicitly stored)

b23

Appendix: Single precision

Page 29: Lecture 3A Data Types: Basic types, Tuples, Polymorphism

Appendix: : Single precision

ü IEEE 754 Format Parameters for single precisionü emax = +127ü emin = -126The reason for having |emin| < emax is so that the reciprocal of the smallest number 1/2'!"# will not overflow. Although it is true that the reciprocal of the largest number will underflow, underflow is usually less serious than overflow.

29

0 0 1 1 1 1 1 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0exponent: 𝐞∗

sign: 𝒔base: 𝒎

238

0222330

1

31= 0.15625.

ü 𝑠𝑖𝑔𝑛 = 𝑏$% = 0,ü −1 &'() = −1 * = +1,ü 𝑒 = 𝑏$*𝑏+,…𝑏+$ = 𝑏+$-*2* + 𝑏+$-%2% +⋯+ 𝑏+$-.2. = 124,ü 2(01%+.) = 2%+31%+. = 21$,ü 1. 𝑏++𝑏+%…𝑏* = 1 + 𝑏+$1%21% + 𝑏+$1+21+ +⋯+ 𝑏+$1+$21+$ = 1 + 1 ⋅ 21+ = 1.25,ü 𝑣𝑎𝑙𝑢𝑒 = +1 ×1.25×21$ = +0.15625.

Page 30: Lecture 3A Data Types: Basic types, Tuples, Polymorphism

Appendix: : Single precision

ü Exampleü Float a = 15213.0;ü 1521310 = 111011011011012 = 1.11011011011012 x 213

ü Significandü m = 1.110110110110100000000002

ü Exponentü 𝐞 = 𝐞∗ – bias = 𝐞∗ – 127 = 13 ü 𝐞∗ = 140 = 100011002

30

0 1 0 0 0 1 1 0 0 1 1 0 1 1 0 1 1 0 1 1 0 1 0 0 0 0 0 0 0 0 0 0

exponent 𝐞∗sign: 𝒔 base: 𝒎

238

0222330

1

31

Page 31: Lecture 3A Data Types: Basic types, Tuples, Polymorphism

Appendix: :Single precision

31

ü Numbers with exponents of 11111111 = 255 = 2128 represent non-numeric quantities such as "not a number" (NaN), returned by operations like (0.0/0.0) and positive or negative infinity

Exponent is 0Exponent is 1

Exponent is -1

Page 32: Lecture 3A Data Types: Basic types, Tuples, Polymorphism

32

Appendix:Double precision representation

𝑣𝑎𝑙𝑢𝑒 = −1 "&!× 1. 𝑏)$𝑏)%…𝑏% #×2 "&$"&"…"'$ $'$%#*

ü The IEEE 754 standard specifies a binary64 (Double in Haskell) as having:ü Sign bit: 1 bitü Exponent width: 11 bitsü Significand (mantissa) precision: 53 bits (52 explicitly stored)

The exponent is in excess-1023 binary notation• Emin (1) = −1022• E (50) = −973• Emax (2046) = 1023

ü 𝑠𝑖𝑔𝑛 = −1 4!"

ü 𝑒 = 𝑏5+𝑏5%…𝑏6+ = 𝑏6+-*2* + 𝑏6+-%2% +⋯+ 𝑏6+-%*2%%,ü 𝑒7 = 2(01%*+$),ü 𝑚 = 1. 𝑏++𝑏+%…𝑏* = 1 + 𝑏6+1%21% + 𝑏6+1+21+ +⋯+ 𝑏6+16+216+,ü 𝑣𝑎𝑙𝑢𝑒 = 𝑠𝑖𝑔𝑛 ×𝑚 × 𝑒7.

b0b63

exponent 𝑒sign: 𝑠 base: 𝑚

b52

Page 33: Lecture 3A Data Types: Basic types, Tuples, Polymorphism

Appendix: American Patriot Missile battery disaster

ü On February 25, 1991, an American Patriot Missile battery failed to track and intercept an incoming missile. 28 soldiers were killed and 100 were injured.

ü The cause was an inaccurate calculation of the time since boot ü Specifically, the time in tenths of second as measured by the system's internal clock

was multiplied by 1/10 to produce the time in seconds. This calculation was performed using a 24 bit fixed point register.

ü The value 1/10, which has a non-terminating binary expansion, was chopped at 24 bits after the radix point. ü the binary expansion of 1/10 is 0.0001100110011001100110011001100ü the 24 bit register in the Patriot stored instead 0.00011001100110011001100ü Error was about 0.000000095 decimalü Multiplying by the number of tenths of a second in 100 hours gives

0.000000095×100×60×60×10=0.34.ü Missile travels 1,676 meters per second, and so travels more than half a kilometer in

this time. This was far enough that the incoming missile was outside the "range gate" that the Patriot tracked.

33

Page 34: Lecture 3A Data Types: Basic types, Tuples, Polymorphism

Appendix: Difference between integer and floating-point numbers

1. An integer has no fractional part; A floating-point number can have a fractional part.

2. Floating-point numbers can represent a much larger range of values than integers can.

3. For some arithmetic operations, such as subtracting one large number from another, floating-point numbers are subject to greater loss of precision.

4. Floating-point values are often approximations of a true value. 5. Floating-point operations are normally slower than integer operations.