Presentation is loading. Please wait.

Presentation is loading. Please wait.

Types CSCE 314 Spring 2016.

Similar presentations


Presentation on theme: "Types CSCE 314 Spring 2016."— Presentation transcript:

1 Types CSCE 314 Spring 2016

2 Why we need types What does this mean?
Is it some integer value? Is it a floating-point number? Is it something else? Types give meaning to a sequence of bits Without types, all data is just a binary string To be useful, all data must have a type associated with it

3 What are types? Types are a collection of (somehow related) values
Enable consistent interpretation of bits Examples: Integers (…, -3, -2, -2, 0, 1, 2, 3, …) Booleans (True or False) For functions, they will take some type as input, and produce some type as output

4 Basic Haskell Types Bool logical values Char single character
String list of characters (enclosed in double quotation marks) Int fixed-precision integer Integer arbitrary precision integer (slower, but any integer) Float single-precision floating point number Double double-precision floating-point number There will be other types to come…

5 Type safety Types can be checked during compilation
Make sure that all steps are using types correctly Inferring types and checking validity prior to execution is called Type Safety An example of an error: 1 + False -- Addition is not defined between a number and a Boolean Benefits of static type checking Detect many classes of errors early-on (compile-time vs. run-time) Faster programs Note: not all languages are type safe

6 Type annotations Often, Haskell can infer the type of an expression (automatically) Add two floats, get a float Compare two floats, get a Boolean Programmers can annotate expressions with types Explicitly indicate what the type of an expression (or later, function) is Sometimes this must be done

7 Making annotations (Expression) :: (Type) Examples:
True :: Bool 2 == 3 :: Bool 5 :: Int -- Actual type is Num a => a (we’ll see later) (2+3) :: Int -- Same here 5 :: Integer -- Notice: some expressions can have many types 5 :: Float -- Again Can use the :type (or just :t) in GHCi to find the type

8 Composite Types Can be built from other types using a type constructor
So, we’re not limited to just basic types Lists and Tuples are most common

9 List types List of values, all of the same type
Type is denoted by type in square brackets [‘a’, ‘b’, ‘c’] :: [Char] “abc” :: [Char] Strings are a list of Chars! [True, True, False, True] :: [Bool] [[True, True], []] :: [[Bool]] Lists are arbitrary length (do not need to define ahead of time) Lists do not have to be finite! l = [1..]

10 Tuple types Sequence of values of possibly different types
Fixed length, and fixed type for each element of sequence Number of elements is its arity Arity 1 tuples are not allowed! Types are listed in parentheses (‘a’, True) :: (Char, Bool) (“Howdy”, 314, ) :: ([Char], Int, Float)

11 Function types Functions map one type (T1) to another type (T2).
That’s right, they map ONE type to ONE other type! Written as T1 -> T2 Examples: not :: Bool -> Bool toUpper :: Char -> Char isAlpha :: Char -> Bool Good to annotate functions at definition (usually on line prior) double :: Int -> Int double x = x + x Can give a function a less general type than what the compiler infers

12 So, how do we define functions with multiple arguments or return values?
One option: Use tuples or lists Can take in or return multiple values Example: adder :: (Int, Int) -> Int adder (a, b) = a+b oneTo :: Int -> [Int] oneTo n = [1..n] The typical Haskell way: currying functions (named after Haskell Curry)

13 Currying Functions Functions return functions
These are called higher order functions We write these as a set of functions, with order implied right to left: a -> b -> c -> d a -> (b -> (c -> d)) This means: The function takes a parameter a, and returns another function That function takes a parameter b, and returns another function That function takes a parameter c, and returns something of type d

14 A simple curried function example
adder a b = a +b This is of type: Int -> Int -> Int Which means it is really Int -> (Int -> Int) So, we have: adder a b (someFunction) b Notice that someFunction will take in b and produce the result

15 Curried Example, continued
So, if we have adder 2 3, this is equivalent to: Applying adder to 2, a new function is created: add2 x = 2+x Then, that function is applied to the remaining argument: add2 3 The end result is = 5

16 More on curried functions
Currying extends to any number of arguments stringify :: Char -> Char -> Char -> Char -> [Char] stringify a b c d = '(':[a] ++ [b] ++ [c] ++ d:[')'] Currying can be partially applied (will see later)

17 Polymorphic functions
If we want a function to take multiple types, we can define a type variable in the function definition These are called polymorphic (“many shapes” functions) Type variables start with any lower case letter, but are usually just a, b, c, etc. length :: [a] -> Int -- Takes a list of any type, a, and returns an Int head :: [a] -> a -- Takes a list of any type, a, and returns something of type a The specific type gets bound at compile time. head [1, 2, 3] a is an Int head [True, False, False, True] -- a is a Bool

18 Example What is the type of this function and what does it do?
twice :: (t -> t) -> t -> t same as: twice :: (t->t) -> (t -> t) twice f x = f (f x) twice tail “abcd” tail (tail “abcd”) tail (“bcd”) “cd”

19 Limiting Polymorphic Functions
A polymorphic function is defined for all types! Means that there are no operations actually done with the type itself What if we want to limit the types? For example, addition is defined for some types, not for others This is where type classes and class constraints come in

20 Overloaded Function Overloaded functions have one or more Class Constraints. A class constraint limits the range of types allowed. Example class: Numerical values, specified by Num Note: we will learn about more classes shortly

21 Class Constraints Can use one or more type classes to limit the types that a polymorphic function can use. Define by putting the class constraint in the type definition for the function <Type class> <type variable> => <function definition using type variable> Example: Num a => a -> a Means that the function is defined for types a, where a is a Num class Can define multiple class constraints by putting in parentheses: (Eq a, Num a) => a -> a

22 Overloaded Function Overloaded functions have one or more Class Constraints. A class constraint limits the range of types allowed. Example class: Numerical values, specified by Num Note: we will learn about more classes shortly sum :: Num a => [a] -> a For any NUMERIC type, a, the function “sum” takes in a list of type a and returns a single value of type a Limits options for list to numeric options sum [1, 5, 9] -- Good sum [2.1, 4.5, 6.9] -- Good sum [‘a’, ‘b’, ‘c’] -- Error

23 Class constraints Needed when there is an operation on values, to determine what operations are legal. If no operations are done on the type, no class constraint needed Basic arithmetic: Num type class (+, -, *, negate, abs, signum) What about checking for equality? Eq type class – allows checking for equality What about checking order (i.e. >, <, etc.) Ord type class (+) :: Num a  a  a  a (==) :: Eq a  a  a  Bool (<) :: Ord a  a  a  Bool

24 Examples -- min selects the smallest element from a list
min :: ??? a => [a] -> a Ord -- elem returns true if an element is in a list, false otherwise elem :: ??? a => a -> [a] -> Bool Eq

25 Haskell 98 Class Hierarchy -- For detailed explanation, refer

26 Key Class types Num Eq Ord Show Read Integral Fractional Enum
Numerical operations Eq Equality and inequality Ord Ordering (comparing >, <) Show Can be converted into a string of characters Read Can be converted from a string of characters Integral Integers, including integer division and remainder Fractional Non-integers (including floats) Enum Enumerated type (can find by n-th element)

27 Hints and Tips When defining a new function in Haskell, begin by writing down its type Within a script, state the type of every function you define When using polymorphic functions, be sure to include the appropriate type class

28 Exercises What are the types of the following values? (1)
[’a’,’b’,’c’] (’a’,’b’,’c’) [(False,’0’),(True,’1’)] ([False,True],[’0’,’1’]) [tail,init,reverse]

29 [Char] [’a’,’b’,’c’] (Char, Char, Char) (’a’,’b’,’c’) [(Bool, Char)] [(False,’0’),(True,’1’)] ([Bool], [Char]) ([False,True],[’0’,’1’]) [[a] -> [a]] [tail,init,reverse]

30 What are the types of the following functions?
(2) What are the types of the following functions? second xs = head (tail xs) swap (x,y) = (y,x) pair x y = (x,y) double x = x*2 palindrome xs = reverse xs == xs lessThanHalf x y = x * 2 < y

31 second :: [a] -> a second xs = head (tail xs) swap :: (a, b) -> (b, a) swap (x,y) = (y,x) pair :: a -> b -> (a, b) pair x y = (x,y) double :: Num a => a -> a double x = x*2 palindrome :: Eq a => [a] -> Bool palindrome xs = reverse xs == xs lessThanHalf :: (Num a, Ord a) => a -> a -> Bool lessThanHalf x y = x * 2 < y


Download ppt "Types CSCE 314 Spring 2016."

Similar presentations


Ads by Google