PROGRAMMING IN HASKELL

Slides:



Advertisements
Similar presentations
15-Jan-15 More Haskell Functions Maybe, Either, List, Set, Map.
Advertisements

Haskell Chapter 6. Modules  A module defines some functions, types, and type classes  A program is a collection of modules  Module used in GHCi is.
Haskell Chapter 7. Topics  Defining data types  Exporting types  Type parameters  Derived instances  Type synonyms  Either  Type classes  Not.
0 PROGRAMMING IN HASKELL Chapter 10 - Declaring Types and Classes.
String is a synonym for the type [Char].
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.
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.
Playing with Haskell Data Neil Mitchell. Overview The “boilerplate” problem Haskell’s weakness (really!) Traversals and queries Generic traversals and.
0 PROGRAMMING IN HASKELL Chapter 11 - Interactive Programs, Declaring Types and Classes.
PrasadCS7761 Haskell Data Types/ADT/Modules Type/Class Hierarchy Lazy Functional Language.
Operators, Functions and Modules1 Pattern Matching & Recursion.
Haskell. 2 GHC and HUGS Haskell 98 is the current version of Haskell GHC (Glasgow Haskell Compiler, version 7.4.1) is the version of Haskell I am using.
0 PROGRAMMING IN HASKELL Based on lecture notes by Graham Hutton The book “Learn You a Haskell for Great Good” (and a few other sources) Modules.
5 BASIC CONCEPTS OF ANY PROGRAMMING LANGUAGE Let’s get started …
Lee CSCE 314 TAMU 1 CSCE 314 Programming Languages Haskell: Types and Classes Dr. Hyunyoung Lee.
0 PROGRAMMING IN HASKELL Chapter 9 - Higher-Order Functions, Functional Parsers.
0 Functors in Haskell Adapted from material by Miran Lipovaca.
16-Nov-15 More Haskell Functions Maybe, Either, List, Set, Map.
0 Odds and Ends in Haskell: Folding, I/O, and Functors Adapted from material by Miran Lipovaca.
0 Modules in Haskell Adapted from material by Miran Lipovaca.
0 PROGRAMMING IN HASKELL Based on lecture notes by Graham Hutton The book “Learn You a Haskell for Great Good” (and a few other sources) Odds and Ends,
More Data Types CSCE 314 Spring CSCE 314 – Programming Studio Defining New Data Types Three ways to define types: 1.type – Define a synonym for.
Haskell. GHC and HUGS Haskell 98 is the current version of Haskell GHC (Glasgow Haskell Compiler, version 7.4.1) is the version of Haskell I am using.
Defining Classes Modules and ADTs CSCE 314 Spring 2016.
1 PROGRAMMING IN HASKELL Lecture 2 Based on lecture notes by Graham Hutton The book “Learn You a Haskell for Great Good” (and a few other sources)
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.
1 PROGRAMMING IN HASKELL Based on lecture notes by Graham Hutton The book “Learn You a Haskell for Great Good” (and a few other sources) Type declarations.
Haskell Chapter 6.
Polymorphic Functions
Week 2 - Wednesday CS 121.
Haskell Chapter 7.
String is a synonym for the type [Char].
Recursion.
Types CSCE 314 Spring 2016.
Haskell Chapter 2.
More Haskell Functions
PROGRAMMING IN HASKELL
Containers and Lists CIS 40 – Introduction to Programming in Python
2.5 Another Java Application: Adding Integers
A lightening tour in 45 minutes
Haskell.
CSE 3302 Programming Languages
More Haskell Functions
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
Encryption and Decryption
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
More Haskell Functions
Tree Rotations and AVL Trees
PROGRAMMING IN HASKELL
Type & Typeclass Syntax in function
Types and Classes in Haskell
PROGRAMMING IN HASKELL
Data Structures and Analysis (COMP 410)
Haskell Types, Classes, and Functions, Currying, and Polymorphism
Haskell Modules Roshan Gunathilake.
PROGRAMMING IN HASKELL
Fundamentals of Functional Programming
More Haskell Functions
CSCE 314: Programming Languages Dr. Dylan Shell
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
Presentation transcript:

PROGRAMMING IN HASKELL Types and Modules Based on lecture notes by Graham Hutton The book “Learn You a Haskell for Great Good” (and a few other sources)

Recap of Typeclasses We have seen typeclasses, which describe classes of data where operations of a certain type make sense. Look more closely at a new example: class Eq a where (==) :: a -> a -> Bool (/=) :: a -> a -> Bool x == y = not (x /= y) x /= y = not (x == y) 1

data TrafficLight = Red | Yellow | Green Now – say we want to make a new type and make sure it belongs to a given typeclass. Here’s how: data TrafficLight = Red | Yellow | Green instance Eq TrafficLight where Red == Red = True Green == Green = True Yellow == Yellow = True _ == _ = False 2

instance Show TrafficLight where show Red = "Red light" Now maybe we want to be able to display these at the prompt. To do this, we need to add this to the “show” class. (Remember those weird errors with the trees yesterday? We hadn’t added trees to this class!) instance Show TrafficLight where show Red = "Red light" show Yellow = "Yellow light" show Green = "Green light" 3

And finally, we can use these things: ghci> Red == Red True ghci> Red == Yellow False ghci> Red `elem` [Red, Yellow, Green] ghci> [Red, Yellow, Green] [Red light,Yellow light,Green light] 4

Arithmetic Expressions Consider a simple form of expressions built up from integers using addition and multiplication. 1 +  3 2

Using recursion, a suitable new type to represent such expressions can be declared by: data Expr = Val Int | Add Expr Expr | Mul Expr Expr For example, the expression on the previous slide would be represented as follows: Add (Val 1) (Mul (Val 2) (Val 3))

Using recursion, it is now easy to define functions that process expressions. For example: size :: Expr  Int size (Val n) = 1 size (Add x y) = size x + size y size (Mul x y) = size x + size y eval :: Expr  Int eval (Val n) = n eval (Add x y) = eval x + eval y eval (Mul x y) = eval x * eval y

The three constructors have types: Note: The three constructors have types: Val :: Int  Expr Add :: Expr  Expr  Expr Mul :: Expr  Expr  Expr Many functions on expressions can be defined by replacing the constructors by other functions using a suitable fold function. For example: eval = fold id (+) (*)

You’ll probably need this: Exercise: Edit our simple expressions to support subtraction and division in eval as well. You’ll probably need this: data Expr = Val Int | Add Expr Expr | Mul Expr Expr deriving Show eval :: Expr  Int eval (Val n) = n eval (Add x y) = eval x + eval y eval (Mul x y) = eval x * eval y Add (Val 1) (Mul (Val 2) (Val 3))

Binary Trees In computing, it is often useful to store data in a two-way branching structure or binary tree. 5 7 9 6 3 4 1

Using recursion, a suitable new type to represent such binary trees can be declared by: data Tree = Leaf Int | Node Tree Int Tree For example, the tree on the previous slide would be represented as follows: Node (Node (Leaf 1) 3 (Leaf 4)) 5 (Node (Leaf 6) 7 (Leaf 9))

We can now define a function that decides if a given integer occurs in a binary tree: occurs :: Int  Tree  Bool occurs m (Leaf n) = m==n occurs m (Node l n r) = m==n || occurs m l || occurs m r But… in the worst case, when the integer does not occur, this function traverses the entire tree.

Now consider the function flatten that returns the list of all the integers contained in a tree: flatten :: Tree  [Int] flatten (Leaf n) = [n] flatten (Node l n r) = flatten l ++ [n] ++ flatten r A tree is a search tree if it flattens to a list that is ordered. Our example tree is a search tree, as it flattens to the ordered list [1,3,4,5,6,7,9].

Search trees have the important property that when trying to find a value in a tree we can always decide which of the two sub-trees it may occur in: occurs m (Leaf n) = m==n occurs m (Node l n r) | m==n = True | m<n = occurs m l | m>n = occurs m r This new definition is more efficient, because it only traverses one path down the tree.

Exercise Node (Node (Leaf 1) 3 (Leaf 4)) 5 (Node (Leaf 6) 7 (Leaf 9)) A binary tree is complete if the two sub-trees of every node are of equal size. Define a function that decides if a binary tree is complete. data Tree = Leaf Int | Node Tree Int Tree occurs :: Int  Tree  Bool occurs m (Leaf n) = m==n occurs m (Node l n r) = m==n || occurs m l || occurs m r

Modules So far, we’ve been using built-in functions provided in the Haskell prelude. This is a subset of a larger library that is provided with any installation of Haskell. (Google for Hoogle to see a handy search engine for these.) Examples of other modules: - lists - concurrent programming - complex numbers - char - sets - …

This is a function in Data.List that removes duplicates from a list. Example: Data.List To load a module, we need to import it: import Data.List  All the functions in this module are immediately available: numUniques :: (Eq a) => [a] -> Int   numUniques = length . nub  This is a function in Data.List that removes duplicates from a list. function concatenation

You can also load modules from the command prompt: ghci> :m + Data.List Or several at once: ghci> :m + Data.List Data.Map Data.Set   Or import only some, or all but some: import Data.List (nub, sort)  import Data.List hiding (nub) 

If duplication of names is an issue, can extend the namespace: import qualified Data.Map This imports the functions, but we have to use Data.Map to use them – like Data.Map.filter. When the Data.Map gets a bit long, we can provide an alias: import qualified Data.Map as M   And now we can just type M.filter, and the normal list filter will just be filter.

ghci> intersperse '.' "MONKEY" "M.O.N.K.E.Y" Data.List has a lot more functionality than we’ve seen. A few examples: ghci> intersperse '.' "MONKEY"   "M.O.N.K.E.Y"   ghci> intersperse 0 [1,2,3,4,5,6]   [1,0,2,0,3,0,4,0,5,0,6] ghci> intercalate " " ["hey","there","guys"]   "hey there guys"   ghci> intercalate [0,0,0] [[1,2,3],[4,5,6], [7,8,9]]   [1,2,3,0,0,0,4,5,6,0,0,0,7,8,9]    20

ghci> transpose [[1,2,3],[4,5,6], [7,8,9]] And even more: ghci> transpose [[1,2,3],[4,5,6], [7,8,9]]   [[1,4,7],[2,5,8],[3,6,9]]   ghci> transpose ["hey","there","guys"] ["htg","ehu","yey","rs","e"]  ghci> concat ["foo","bar","car"]   "foobarcar"   ghci> concat [[3,4,5],[2,3,4],[2,1,1]]   [3,4,5,2,3,4,2,1,1]    21

ghci> and $ map (>4) [5,6,7,8] True And even more: ghci> and $ map (>4) [5,6,7,8]   True   ghci> and $ map (==4) [4,4,4,3,4]   False   ghci> any (==4) [2,3,5,6,1,4]   True   ghci> all (>4) [6,9,10]   True      22

A nice example: adding functions Functions are often represented as vectors: 8x^3 + 5x^2 + x - 1 is [8,5,1,-1]. So we can easily use List functions to add these vectors: ghci> map sum $ transpose [[0,3,5,9], [10,0,0,9],[8,5,1,-1]]   [18,8,6,17] 23

There are a ton of these functions, so I could spend all semester covering just lists. More examples: group, sort, dropWhile, takeWhile, partition, isPrefixOf, find, findIndex, delete, words, insert,… Instead, I’ll make sure to post a link to a good overview of lists on the webpage, in case you need them. In essence, if it’s a useful thing to do to a list, Haskell probably supports it! 24

Examples: isAlpha, isLower, isSpace, isDigit, isPunctuation,… The Data.Char module: includes a lot of useful functions that will look similar to python, actually. Examples: isAlpha, isLower, isSpace, isDigit, isPunctuation,… ghci> all isAlphaNum "bobby283"   True   ghci> all isAlphaNum "eddy the fish!"False  ghci> groupBy ((==) `on` isSpace)  "hey guys its me"   ["hey"," ","guys"," ","its"," ","me"] 25

The Data.Char module has a datatype that is a set of comparisons on characters. There is a function called generalCategory that returns the information. (This is a bit like the Ordering type for numbers, which returns LT, EQ, or GT.) ghci> generalCategory ' '   Space   ghci> generalCategory 'A'   UppercaseLetter   ghci> generalCategory 'a'   LowercaseLetter   ghci> generalCategory '.'   OtherPunctuation   ghci> generalCategory '9'   DecimalNumber   ghci> map generalCategory " ¥t¥nA9?|"   [Space,Control,Control,UppercaseLetter,DecimalNumber,OtherPunctuation,MathSymbol]  ] 26

There are also functions that can convert between Ints and Chars: ghci> map digitToInt "FF85AB"   [15,15,8,5,10,11] ghci> intToDigit 15   'f'   ghci> intToDigit 5   '5'    ghci> chr 97   'a'   ghci> map ord "abcdefgh"   [97,98,99,100,101,102,103,104]  27

Neat application: Ceasar ciphers A primitive encryption cipher which encodes messages by shifted them a fixed amount in the alphabet. Example: hello with shift of 3 encode :: Int -> String -> String   encode shift msg =      let ords = map ord msg           shifted = map (+ shift) ords       in  map chr shifted   28

ghci> encode 3 "Heeeeey" "Khhhhh|" ghci> encode 4 "Heeeeey" Now to use it: ghci> encode 3 "Heeeeey"   "Khhhhh|"   ghci> encode 4 "Heeeeey"   "Liiiii}"   ghci> encode 1 "abcd"   "bcde"   ghci> encode 5 "Marry Christmas! Ho ho ho!” "Rfww~%Hmwnxyrfx&%Mt%mt%mt&"   29

Decoding just reverses the encoding: decode :: Int -> String -> String   decode shift msg =  encode (negate shift) msg     ghci> encode 3 "Im a little teapot"   "Lp#d#olwwoh#whdsrw"   ghci> decode 3 "Lp#d#olwwoh#whdsrw"   "Im a little teapot"   ghci> decode 5 . encode 5 $ "This is a sentence"   "This is a sentence"      30

Making our own modules We specify our own modules at the beginning of a file. For example, if we had a set of geometry functions: module Geometry   ( sphereVolume   , sphereArea   , cubeVolume   , cubeArea   , cuboidArea   , cuboidVolume   ) where 

Then, we put the functions that the module uses: sphereVolume :: Float -> Float   sphereVolume radius = (4.0 / 3.0) * pi *  (radius ^ 3)   sphereArea :: Float -> Float   sphereArea radius = 4 * pi * (radius ^ 2)   cubeVolume :: Float -> Float   cubeVolume side = cuboidVolume side side side  … 32

Note that we can have “private” helper functions, also: cuboidVolume :: Float -> Float -> Float  -> Float   cuboidVolume a b c = rectangleArea a b * c  cuboidArea :: Float -> Float ->  Float -> Float   cuboidArea a b c = rectangleArea a b * 2 + rectangleArea a c * 2 + rectangleArea c b * 2   rectangleArea :: Float -> Float -> Float   rectangleArea a b = a * b  33

Each will hold a separate group of functions. To load: Can also nest these. Make a folder called Geometry, with 3 files inside it: Sphere.hs Cubiod.hs Cube.hs Each will hold a separate group of functions. To load: import Geometry.Sphere Or (if functions have same names): import qualified Geometry.Sphere as Sphere 34

module Geometry.Sphere ( volume , area ) where The modules: module Geometry.Sphere   ( volume   , area   ) where   volume :: Float -> Float   volume radius = (4.0 / 3.0) * pi * (radius ^ 3)   area :: Float -> Float   area radius = 4 * pi * (radius ^ 2) 35

module Geometry.Cuboid ( volume , area ) where volume :: Float -> Float -> Float -> Float   volume a b c = rectangleArea a b * c   …   36