Haskell Chapter 2.

Slides:



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

Haskell Chapter 7. Topics  Defining data types  Exporting types  Type parameters  Derived instances  Type synonyms  Either  Type classes  Not.
ML: a quasi-functional language with strong typing Conventional syntax: - val x = 5; (*user input *) val x = 5: int (*system response*) - fun len lis =
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)
0 PROGRAMMING IN HASKELL Chapter 3 - Types and Classes.
Chapter 12 Qualified Types. Motivation  What should the principal type of (+) be? Int -> Int -> Int-- too specific a -> a -> a-- too general  It seems.
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.
Multiple Choice Solutions True/False a c b e d   T F.
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.
Operators, Functions and Modules1 Pattern Matching & Recursion.
0 REVIEW OF HASKELL A lightening tour in 45 minutes.
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
CPS120: Introduction to Computer Science
5 BASIC CONCEPTS OF ANY PROGRAMMING LANGUAGE Let’s get started …
1 Functional Programming Lecture 6 - Algebraic Data Types.
Introduction to Java Java Translation Program Structure
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: True.
Introduction to Generics
© M. Winter COSC 4P41 – Functional Programming Modules in Haskell Using modules to structure a large program has a number of advantages: Parts of.
Copyright Curt Hill Variables What are they? Why do we need them?
School of Computer Science & Information Technology G6DICP - Lecture 4 Variables, data types & decision making.
This In Java, the keyword this allows an object to refer to itself. Or, in other words, this refers to the current object – the object whose method or.
Announcements Assignment 2 Out Today Quiz today - so I need to shut up at 4:25 1.
Copyright 2006 Pearson Addison-Wesley, 2008, 2012 Joey Paquet 1 Concordia University Department of Computer Science and Software Engineering SOEN6441 –
Java Generics. Lecture Objectives To understand the objective of generic programming To be able to implement generic classes and methods To know the limitations.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
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.
6-Jul-16 Haskell II Functions and patterns. Data Types Int + - * / ^ even odd Float + - * / ^ sin cos pi truncate Char ord chr isSpace isUpper … Bool.
Polymorphic Functions
Chapter VII: Arrays.
Functional Programming
EGR 2261 Unit 11 Pointers and Dynamic Variables
Java Generics.
Haskell Chapter 7.
PROGRAMMING IN HASKELL
Types CSCE 314 Spring 2016.
ML: a quasi-functional language with strong typing
MPCS 51400: Functional Programming
Lecture 5: Some more Java!
Functions and patterns
Agenda Warmup AP Exam Review: Litvin A2
More About Objects and Methods
A lightening tour in 45 minutes
Computer Science 3 Hobart College
CSE 3302 Programming Languages
Wrapper Classes ints, doubles, and chars are known as primitive types, or built-in types. There are no methods associated with these types of variables.
IDENTIFIERS CSC 111.
Numbers.
Variables Numbers can be stored and retrieved while a program is running if they are given a home. The way that integers and decimal numbers are stored.
Chapter 2: Java Fundamentals
Variables Title slide variables.
Type & Typeclass Syntax in function
Coding Concepts (Data- Types)
Types and Classes in Haskell
CSCE 314: Programming Languages Dr. Dylan Shell
Chapter # 2 Part 2 Programs And data
Haskell Types, Classes, and Functions, Currying, and Polymorphism
Records and Type Classes
Functions and patterns
PROGRAMMING IN HASKELL
In this class, we will cover:
Primitive Types and Expressions
Review: libraries and packages
Functions and patterns
PROGRAMMING IN HASKELL
Variables in C Topics Naming Variables Declaring Variables
PROGRAMMING IN HASKELL
Arrays.
Records and Type Classes
Presentation transcript:

Haskell Chapter 2

Chapter 2 Type inference Type variables Type classes

Type inference

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.

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

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…

Type variables

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

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)

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!

Type classes

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.”

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

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

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

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.

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

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

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

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] + 5.5 – Error! fromIntegral (length [1,2,3]) + 5.5 8.5 https://wiki.haskell.org/Converting_numbers

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