Grab Bag of Interesting Stuff. Topics Higher kinded types Files and handles IOError Arrays.

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 Datatypes.1 Standard ML Data types. ML Datatypes.2 Concrete Datatypes  The datatype declaration creates new types  These are concrete data types,
Kathleen Fisher cs242 Reading: “A history of Haskell: Being lazy with class”,A history of Haskell: Being lazy with class Section 6.4 and Section 7 “Monads.
ML: a quasi-functional language with strong typing Conventional syntax: - val x = 5; (*user input *) val x = 5: int (*system response*) - fun len lis =
Chapter 16 Communicating With the Outside World. Motivation  In Chapter 3 we learned how to do basic IO, but it was fairly limited.  In this chapter.
Functional Programming Universitatea Politehnica Bucuresti Adina Magda Florea
Chapter 3 Simple Graphics. Side Effects and Haskell  All the programs we have seen so far have no “side-effects.” That is, programs are executed only.
A Lightning Tour of Haskell Lecture 1, Designing and Using Combinators John Hughes.
ML: a quasi-functional language with strong typing Conventional syntax: - val x = 5; (*user input *) val x = 5: int (*system response*) - fun len lis =
Comp 205: Comparative Programming Languages User-Defined Types Enumerated types Parameterised types Recursive types Lecture notes, exercises, etc., can.
Advanced Programming Handout 9 Qualified Types (SOE Chapter 12)
Advanced Programming Handout 12 Higher-Order Types (SOE Chapter 18)
Cse536 Functional Programming 1 6/23/2015 Lecture #17, Dec. 1, 2004 Todays Topics – Higher Order types »Type constructors that take types as arguments.
Chapter 5 Polymorphic and Higher-Order Functions.
Cse536 Functional Programming 1 6/30/2015 Lecture #16, Nov. 29, 2004 Todays Topics – Files, Channels, and Handles –IO exception handling –First Class Channels.
Chapter 12 Qualified Types. Motivation  What should the principal type of (+) be? Int -> Int -> Int-- too specific a -> a -> a-- too general  It seems.
CS510AP Quick Check Monads. QuickCheck Quick check is a Haskell library for doing random testing. You can read more about quickcheck at –
0 PROGRAMMING IN HASKELL Chapter 9 - Interactive Programs.
0 PROGRAMMING IN HASKELL Chapter 11 - Interactive Programs, Declaring Types and Classes.
PrasadCS7761 Haskell Data Types/ADT/Modules Type/Class Hierarchy Lazy Functional Language.
Workshop: Towards Highly Portable Software Jakarta, 21 – 23 January 2003 Diselenggarakan oleh Universitas IndonesiaUniversitas Indonesia Part 1 : Programming.
ML Datatypes.1 Standard ML Data types. ML Datatypes.2 Concrete Datatypes  The datatype declaration creates new types  These are concrete data types,
Advanced Functional Programming 2009 Ulf Norell (lecture by Jean-Philippe Bernardy)
Lee CSCE 314 TAMU 1 CSCE 314 Programming Languages Haskell: Types and Classes Dr. Hyunyoung Lee.
1-Nov-15 Haskell II Functions and patterns. Data Types Int + - * / ^ even odd Float + - * / ^ sin cos pi truncate Char ord chr isSpace isUpper … Bool.
1 Functional Programming Lecture 6 - Algebraic Data Types.
Overview of the Haskell 98 Programming Language
0 Functors in Haskell Adapted from material by Miran Lipovaca.
© M. Winter COSC 4P41 – Functional Programming Programming with actions Why is I/O an issue? I/O is a kind of side-effect. Example: Suppose there.
0 Odds and Ends in Haskell: Folding, I/O, and Functors Adapted from material by Miran Lipovaca.
Arvind Computer Science and Artificial Intelligence Laboratory M.I.T. L13-1 October 26, 2006http:// Monadic Programming October.
1 Haskell Kevin Atkinson John Simmons. 2 Contents Introduction Type System Variables Functions Module System I/O Conclusions.
1 CS 457/557: Functional Languages Lists and Algebraic Datatypes Mark P Jones Portland State University.
Lee CSCE 314 TAMU 1 CSCE 314 Programming Languages Interactive Programs: I/O and Monads Dr. Hyunyoung Lee.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Grab Bag of Interesting Stuff. Higher Order types Type constructors are higher order since they take types as input and return types as output. Some type.
Haskell Chapter 9. More Input and More Output  Files and Streams  Transforming Input  Not covered  brackets  command-line arguments  bytestrings.
Advanced Functional Programming Tim Sheard 1 Lecture 6 Advanced Functional Programming Tim Sheard Oregon Graduate Institute of Science & Technology Lecture.
An introduction to functional programming using Haskell CENG242 –Recitation 1.
24-Jun-16 Haskell Dealing with impurity. Purity Haskell is a “pure” functional programming language Functions have no side effects Input/output is a side.
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.
Advanced Functional Programming 2010
Set Comprehensions In mathematics, the comprehension notation can be used to construct new sets from old sets. {x2 | x  {1...5}} The set {1,4,9,16,25}
Set Comprehensions In mathematics, the comprehension notation can be used to construct new sets from old sets. {x2 | x  {1...5}} The set {1,4,9,16,25}
Haskell Chapter 7.
Types CSCE 314 Spring 2016.
PROGRAMMING IN HASKELL
Haskell Chapter 9.
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
I/O in C Lecture 6 Winter Quarter Engineering H192 Winter 2005
Haskell Dealing with impurity 30-Nov-18.
Haskell Dealing with impurity 30-Nov-18.
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
Advanced Functional Programming
Types and Classes in Haskell
Input and Output.
PROGRAMMING IN HASKELL
Haskell Dealing with impurity 8-Apr-19.
PROGRAMMING IN HASKELL
Grab Bag of Interesting Stuff
Programming Languages
Haskell Dealing with impurity 29-May-19.
PROGRAMMING IN HASKELL
Haskell Dealing with impurity 28-Jun-19.
PROGRAMMING IN HASKELL
Advanced Functional Programming
Presentation transcript:

Grab Bag of Interesting Stuff

Topics Higher kinded types Files and handles IOError Arrays

Higher Order types Type constructors are higher order since they take types as input and return types as output. Some type constructors (and also some class definitions) are even higher order, since they take type constructors as arguments. Haskell’s Kind system – A Kind is haskell’s way of “typing” types – Ordinary types have kind * Int :: * [ String ] :: * – Type constructors have kind * -> * Tree :: * -> * [] :: * -> * (,) :: * -> * -> *

The Functor Class class Functor f where fmap :: (a -> b) -> (f a -> f b) Note how the class Functor requires a type constructor of kind * -> * as an argument. The method fmap abstracts the operation of applying a function on every parametric Argument. a Type T a = x (f x) fmap f

Notes Special syntax for built in type constructors (->) :: * -> * -> * [] :: * -> * (,) :: * -> * -> * (,,) :: * -> * -> * -> * Most class definitions have some implicit laws that all instances should obey. The laws for Functor are: fmap id = id fmap (f. g) = fmap f. fmap g

Instances of class functor data Tree a = Leaf a | Branch (Tree a) (Tree a) instance Functor Tree where fmap f (Leaf x) = Leaf (f x) fmap f (Branch x y) = Branch (fmap f x) (fmap f y) instance Functor ((,) c) where fmap f (x,y) = (x, f y)

More Instances instance Functor [] where fmap f [] = [] fmap f (x:xs) = f x : fmap f xs instance Functor Maybe where fmap f Nothing = Nothing fmap f (Just x) = Just (f x)

Other uses of Higher order T.C.’s data Tree t a = Tip a | Node (t (Tree t a)) t1 = Node [Tip 3, Tip 0] Main> :t t1 t1 :: Tree [] Int data Bin x = Two x x t2 = Node (Two(Tip 5) (Tip 21)) Main> :t t2 t2 :: Tree Bin Int

What is the kind of Tree? Tree is a binary type constructor – It’s kind will be something like: ? -> ? -> * The first argument to Tree is itself a type constructor, the second is just an ordinary type. – Tree :: (* -> *)-> * -> *

Functor instances of Tree instance Functor (Tree2 Bin) where fmap f (Tip x) = Tip(f x) fmap f (Node (Two x y)) = Node (Two (fmap f x) (fmap f y)) instance Functor (Tree2 []) where fmap f (Tip x) = Tip(f x) fmap f (Node xs) = Node (map (fmap f) xs)

Can we do better instance Functor t => Functor (Tree2 t) where fmap f (Tip x) = Tip(f x) fmap f (Node xs) = Node (fmap (fmap f) xs)

The Monad Class class Monad m where (>>=) :: m a -> (a -> m b) -> m b (>>) :: m a -> m b -> m b return :: a -> m a fail :: String -> m a p >> q = p >>= \ _ -> q fail s = error s Note m is a type constructor

Generic Monad functions sequence :: Monad m => [m a] -> m [a] sequence = foldr mcons (return []) where mcons p q = do x <- p xs <- q return (x:xs) sequence_ :: Monad m => [m a] -> m () sequence_ = foldr (>>) (return ()) mapM :: Monad m => (a -> m b) -> [a] -> m [b] mapM f as = sequence (map f as) mapM_ :: Monad m => (a -> m b) -> [a] -> m () mapM_ f as = sequence_ (map f as) (= (a -> m b) -> m a -> m b f = >= f

Files and Handles The functions: import System.IO writeFile :: FilePath -> String -> IO () appendFile :: FilePath -> String -> IO () are used to read and write to files, but they incur quite a bit of overhead if they are used many times in a row. Instead we wish to open a file once, then make many actions on the file before we close it for a final time. openFile :: FilePath -> IOMode -> IO Handle hClose :: Handle -> IO () data IOMode = ReadMode | WriteMode | AppendMode deriving (Eq, Ord, Ix, Bounded, Enum, Read, Show)

File Modes A file mode tells how an open file will be used. Different modes support different operations. When in WriteMode hPutChar :: Handle -> Char -> IO () hPutStr :: Handle -> String -> IO () hPutStrLn :: Handle -> String -> IO () hPrint :: Show a => Handle -> a -> IO () When in ReadMode hGetChar :: Handle -> IO Char hGetLine :: Handle -> IO String

Standard Channels and Errors Predefined standard Channels stdin, stdout, stderr :: Handle Error Handling while doing IO isEOFError :: IOError -> Bool -- Test if the EOF error ioError :: IOError -> IO a -- Raise an IOError catch :: IO a -> (IOError -> IO a) -> IO a -- Handle an Error Other IO types of errors and their predicates. isAlreadyExistsError, isDoesNotExistError, isAlreadyInUseError, isFullError, isEOFError, isIllegalOperation, isPermissionError, isUserError,

IOError IOError is an abstract datatype – NOT and algebraic datatype, defined with data like [ ] or Tree Thus it does not admit pattern matching. Hence the use of all the IOError recognizing predicates. – isAlreadyExistsError, isDoesNotExistError, – isAlreadyInUseError, isFullError, – isEOFError, isIllegalOperation, – isPermissionError, isUserError This was a concious decision, made to allow easy extension of the kinds of IOErrors, as the system grew.

Handling IO Errors Any action of type IO a may potentially cause an IO Error. The function catch :: IO a -> (IOError -> IO a) -> IO a can be used to gracefully handle such an error by providing a “fix” getChar' :: IO Char getChar' = catch getChar (\ e -> return '\n') getChar2 :: IO Char getChar2 = catch getChar (\ e -> if isEOFError e then return '\n' else ioError e) –- pass non EOF errors on

An Example getLine' :: IO String getLine' = catch getLine'' (\ e -> return ("Error: " ++ show e)) where getLine'' = do { c <- getChar2 ; if c == '\n' then return "" else do { l <- getLine' ; return (c:l) }

Catching errors when opening files getAndOpenFile :: String -> IOMode -> IO Handle getAndOpenFile prompt mode = do { putStr prompt ; name <- getLine ; catch (openFile name mode) (\e -> do { putStrLn ("Cannot open: "++name) ; print e ; getAndOpenFile prompt mode }) }

Copying Files main = do { fromHandle <- getAndOpenFile "Copy from: " ReadMode ; toHandle <- getAndOpenFile "Copy to: " WriteMode ; contents <- hGetContents fromHandle ; hPutStr toHandle contents ; hClose fromHandle ; hClose toHandle ; putStr "Done\n" }

Arrays x :: Array index elem In Haskell we have pure arrays Created in linear time Access in constant time Indexed by many things Store anything (polymorphic elem)

Indexing Arrays are indexed by scalar types The class (Ix t) describes types that can be used as indexes class Ord a => Ix a where range :: (a, a) -> [a] index :: (a, a) -> a -> Int inRange :: (a, a) -> a -> Bool rangeSize :: (a, a) -> Int

Ix instances instance Ix Integer instance Ix Int instance Ix Char instance Ix Bool instance (Ix a, Ix b) => Ix (a, b)

Deriving Ix for enumerations data Color = Red | Blue | Green | Yellow | White | Black deriving (Ord,Eq,Ix) * > range (Red,Black) [Red,Blue,Green,Yellow,White,Black] *> index (Red,Black) Yellow 3 *> index (Yellow,Black) Yellow 0 *> rangeSize (Yellow,Black) 3

Creating arrays by listing listArray :: (Ix i) => (i, i) -> [e] -> Array i eIx digits = listArray (0,9) " "

Creating arrays by tagging array :: (Ix i) => (i, i)Ix -- bounds of the array: -- (lowest,highest) -> [(i, e)] -- list of associations -> Array i e alphabet = array (1,26) (zip [1..26] "abcdefghijklmnopqrstuvwxyz") fifth = alphabet ! 5

Accessing arrays (!) :: (Ix i) => a i e -> i -> eIx – Returns the element of an immutable array at the specified index. indices :: (Ix i) => a i e -> [i]Ix – Returns a list of all the valid indices in an array. elems :: (Ix i) => a i e -> [e]Ix – Returns a list of all the elements of an array, in the same order as their indices. assocs :: (Ix i) => a i e -> [(i, e)]Ix – Returns the contents of an array as a list of associations.

Multiple Array libraries There are many array libraries that share the same interface class IArray a e where Class of immutable array types. An array type has the form (a i e) where a is the array type constructor (kind * -> * -> *), i is the index type (a member of the class Ix), and e is the element type. The IArray class is parameterised over both a and e, so that instances specialized to certain element types can be defined.Ix

Compare listArray :: (Iarray a e, Ix i) => (i, i) -> [e] -> a i eaIx Compare to listArray :: (Ix i) => (i, i) -> [e] -> Array i eIx

Use Array use generally follows a pattern 1.Create a list of array elements Comprehensions are very useful here 2.Create the Array from the list using array or listArray 3.Enter a mode where the many things are looked up in the array in constant time.