Presentation is loading. Please wait.

Presentation is loading. Please wait.

Haskell Chapter 2.

Similar presentations


Presentation on theme: "Haskell Chapter 2."— Presentation transcript:

1 Haskell Chapter 2

2 Chapter 2 Type inference Type variables Type classes

3 Type inference

4 What type is that? :t expression => type :t ‘a’ :t [ ] :t [ 1,2,3]
‘a’ :: Char read “a has type of Char” :t [ ] [] :: [a] [] denotes a list :t [ 1,2,3] [1,2,3] :: Num t => [t] tuples have unique types :t (1,2) (1,2) :: (Num t1, Num t) => (t, t1) We’ll come back to this later and these signatures will make more sense.

5 Specify type declaration for fn
removeNonUpperCase :: [Char] -> [Char] removeNonUppercase st = [c | c <- st, c `elem` ['A'..'Z']] takes a list of characters, returns a list of characters addThree :: Int -> Int -> Int -> Int addThree x y z = x + y + z takes 3 integers, returns an integer Syntax for addThree is covered in chapter 5

6 Common Data Types Type names start with capital letters.
Int. Bounded whole number. Integer. Really big whole numbers. Float. Single precision. Double. Double precision. Bool. True and False. Char. Unicode character. Tuples. Also empty tuple (). Don’t begin your function names with upper case! Notice: Num is not a type. So what is it? We’ll see…

7 Type variables

8 Type variables/Polymorphic types
Some functions can operate on various types (e.g., list functions) :t head head :: [a] -> a Takes a list of any type, returns that type Notice the type variable (a) is lower case Convention is to use 1-character names for type vars Type variable will be instantiated with a DataType a could be Integer (head [1,2,3]) a could be Float (head [1.4, 5.2]) a could be Char (head [‘a’,’b’,’x’]) Type variables facilitate polymorphism! compare to regular variable, which is instantiated with data value

9 Another example :t fst fst :: (a, b) -> a
Notice two different letters, types don’t need to match fst(‘a’,1) fst(3.5, True) They can match (a can be instantiated to same type as b) fst(1,2)

10 Type variable vs variable
head :: [a] -> a a could be instantiated with any data type (e.g., Integer) int x = 5; x is instantiated with a data value Also compare to Java parameterized type: Class ArrayList<E> E can be Point E can be Integer E can be String E cannot be 5!

11 Type classes

12 Type classes Interface that defines some behavior
If a type is an instance of that type class, then it supports that behavior :t (==) (==) :: Eq a => a -> a -> Bool => is a class constraint class constraint – means a cannot be just any type, but it must be a type that has needed behavior similar to Java: Collections.sort(Comparable); anything that can be compared can be sorted Parameters to == MUST have the ability to be compared Read as: “The equality function takes two values that are of the same type and returns a Bool. The type of those two values must be an instance of the Eq class.”

13 Type classes, continued
The built-in types (Int, etc.) belong to the class Eq If you create a new type (chapter 7), items cannot be compared unless you specify they belong to Eq Roughly similar to implementing an interface But syntax is very different! Contrast with duck typing – interpreter just looks for a function, if it’s there it uses it. Here, you must specify that the behavior exists – so more like Java interface

14 Common Type Classes Eq Ord == and /=
an Eq constraint for a type variable means the function uses == or /= somewhere in its definition :t elem elem :: Eq a => a -> [a] -> Bool Ord Values can be put in some order >, <, >=,<=,compare Being an Eq is a prereq for Ord

15 Common Type Classes, continued
Show values can be represented as strings (sort of like having a toString) commonly used by show, e.g., show 3 => “3” cannot “show” a function may also see this type of error if what you return from a function is not an instance of show *Main> show removeNonUppercase <interactive>:39:1: No instance for (Show ([Char] -> [Char])) arising from a use of `show' Possible fix: add an instance declaration for (Show ([Char] -> [Char])) In the expression: show removeNonUppercase In an equation for `it': it = show removeNonUppercase

16 Common Type Classes, continued
Read Takes a string and returns a value whose type is an instance of Read read "2" + 4.5 Needs to know what type to return, can’t just do: read "2" Can use type annotation: read "2" :: Int Remember: Haskell is statically typed. Doesn’t actually “read” until execution… but type needs to be decided at compile time.

17 Common Type Classes, continued
Enum Sequentially ordered types Values can be enumerated Have defined successors (succ) and predecessors (pred) (), Bool, Char, Ordering, Int, Integer, Float, Double are Enum Bounded minBound and maxBound maxBound :: Int

18 Common Type Classes, continued
Num numeric, instances act like numbers :t 20 20 :: Num a => a a is a type variable Num a adds a constraint Called polymorphic constants :t (+) (+) :: Num a => a -> a -> a NOTE: Num a is no longer Show a. Sometimes you need both in the type declaration, e.g., (Num a, Show a) => (a, a) -> a This will make more sense as we look at function signatures in upcoming chapters

19 Common Type Classes, continued
Integral Includes only whole numbers (Int and Integer) Fractional Includes numbers with decimal (Float and Double)

20 fromIntegral Haskell doesn’t convert integral to floating point automatically. fromIntegral :: (Integral a, Num b) => a -> b Different class constraints (a is whole #, b is #) Takes an integral value and converts it into more general number :t length length :: [a] -> Int length [1,2,3] – Error! fromIntegral (length [1,2,3]) + 5.5 8.5

21 Play (no share) Spend ~5 minutes tryout the :t command
play with show and read play with fromIntegral


Download ppt "Haskell Chapter 2."

Similar presentations


Ads by Google