PROGRAMMING IN HASKELL

Slides:



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

Haskell Chapter 7. Topics  Defining data types  Exporting types  Type parameters  Derived instances  Type synonyms  Either  Type classes  Not.
Functional Programming Universitatea Politehnica Bucuresti Adina Magda Florea
Grab Bag of Interesting Stuff. Topics Higher kinded types Files and handles IOError Arrays.
Advanced Programming Handout 12 Higher-Order Types (SOE Chapter 18)
Introduction to ML - Part 2 Kenny Zhu. What is next? ML has a rich set of structured values Tuples: (17, true, “stuff”) Records: {name = “george”, age.
Cse536 Functional Programming 1 6/23/2015 Lecture #17, Dec. 1, 2004 Todays Topics – Higher Order types »Type constructors that take types as arguments.
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.
Haskell Chapter 8. Input and Output  What are I/O actions?  How do I/O actions enable us to do I/O?  When are I/O actions actually performed?
Instructor: Chris Trenkov Hands-on Course Python for Absolute Beginners (Spring 2015) Class #005 (April somthin, 2015)
Collecting Things Together - Lists 1. We’ve seen that Python can store things in memory and retrieve, using names. Sometime we want to store a bunch of.
0 Functors in Haskell Adapted from material by Miran Lipovaca.
16-Nov-15 More Haskell Functions Maybe, Either, List, Set, Map.
© 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.
Lee CSCE 314 TAMU 1 CSCE 314 Programming Languages Interactive Programs: I/O and Monads Dr. Hyunyoung Lee.
CMSC 330: Organization of Programming Languages Operational Semantics a.k.a. “WTF is Project 4, Part 3?”
ICS3U_FileIO.ppt File Input/Output (I/O)‏ ICS3U_FileIO.ppt File I/O Declare a file object File myFile = new File("billy.txt"); a file object whose name.
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.
CMSC 330: Organization of Programming Languages Operational Semantics.
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.
11 Making Decisions in a Program Session 2.3. Session Overview  Introduce the idea of an algorithm  Show how a program can make logical decisions based.
Polymorphic Functions
Haskell Chapter 8.
Haskell Chapter 7.
More about comments Review Single Line Comments The # sign is for comments. A comment is a line of text that Python won’t try to run as code. Its just.
Haskell: Syntax in Functions
Recursion.
Types CSCE 314 Spring 2016.
Introduction to Python
Theory of Computation Lecture 4: Programs and Computable Functions II
More Haskell Functions
Introduction to Computer Science / Procedural – 67130
PROGRAMMING IN HASKELL
More Haskell Functions
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
Subroutines Idea: useful code can be saved and re-used, with different data values Example: Our function to find the largest element of an array might.
Strings, Line-by-line I/O, Functions, Call-by-Reference, Call-by-Value
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
Conditions and Ifs BIS1523 – Lecture 8.
PROGRAMMING IN HASKELL
Haskell Dealing with impurity 30-Nov-18.
CISC101 Reminders Assn 3 due tomorrow, 7pm.
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
Introduction to Primitive Data types
More Haskell Functions
PROGRAMMING IN HASKELL
Type & Typeclass Syntax in function
Advanced Functional Programming
Input and Output.
Fundamentals of Functional Programming
RECURSION Haskell.
More Haskell Functions
Haskell Dealing with impurity 8-Apr-19.
Grab Bag of Interesting Stuff
PROGRAMMING IN HASKELL
Programming Languages
Computer Science 312 I/O and Side Effects 1.
Haskell Dealing with impurity 29-May-19.
CISC101 Reminders Assignment 3 due today.
PROGRAMMING IN HASKELL
Haskell Dealing with impurity 28-Jun-19.
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
Introduction to Primitive Data types
Presentation transcript:

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

File I/O So far, we’ve worked mainly at the prompt, and done very little true input or output. This is logical in a functional language, since nothing has side effects! However, this is a problem with I/O, since the whole point is to take input (and hence change some value) and then output something (which requires changing the state of the screen or other I/O device. Luckily, Haskell offers work-arounds that separate the more imperative I/O.

A simple example: save the following file as helloword.hs main = putStrLn "hello, world" Now we actually compile a program: $ ghc --make helloworld   [1 of 1] Compiling Main        ( helloworld.hs, helloworld.o )   Linking helloworld ...      $ ./helloworld   hello, world  2

What are these functions? ghci> :t putStrLn   putStrLn :: String -> IO ()   ghci> :t putStrLn "hello, world"   putStrLn "hello, world" :: IO ()  So putStrLn takes a string and returns an I/O action (which has a result type of (), the empty tuple). In Haskell, an I/O action is one with a side effect - usually either reading or printing. Usually some kind of a return value, where () is a dummy value for no return. 3

A more interesting example: An I/O action will only be performed when you give it the name “main” and then run the program. A more interesting example: main = do       putStrLn "Hello, what's your name?”       name <- getLine       putStrLn ("Hey " ++ name ++ ",  you rock!")    Notice the do statement - more imperative style. Each step is an I/O action, and these glue together. 4

More on getLine: ghci> :t getLine getLine :: IO String This is the first I/O we’ve seen that doesn’t have an empty tuple type - it has a String. Once the string is returned, we use the <- to bind the result to the specified identifier. Notice this is the first non-functional action we’ve seen, since this function will NOT have the same value every time it is run! This is called “impure” code, and the value name is “tainted”. 5

nameTag = "Hello, my name is " ++ getLine An invalid example: nameTag = "Hello, my name is " ++ getLine  What’s the problem? Well, ++ requires both parameters to have the same type. What is the return type of getLine? Another word of warning: what does the following do? name = getLine    6

ghci> putStrLn "HEEY" HEEY Just remember that I/O actions are only performed in a few possible places: A main function inside a bigger I/O block that we have composed with a do (and remember that the last action can’t be bound to a name, since that is the one that is the return type). At the ghci prompt: ghci> putStrLn "HEEY"   HEEY     7

Note that <- is for I/O, and let for expressions. You can use let statements inside do blocks, to call other functions (and with no “in” part required): import Data.Char  main = do       putStrLn "What's your first name?"       firstName <- getLine       putStrLn "What's your last name?"       lastName <- getLine       let bigFirstName = map toUpper firstName           bigLastName = map toUpper lastName       putStrLn $ "hey " ++ bigFirstName ++ " " ++  bigLastName ++ ", how are you?"     Note that <- is for I/O, and let for expressions. 8

What is return? Does NOT signal the end of execution! Return instead makes an I/O action out of a pure value. main = do       a <- return "hell"       b <- return "yeah!"       putStrLn $ a ++ " " ++ b   In essence, return is the opposite of <-. Instead of “unwrapping” I/O Strings, it wraps them. 9

Last example was a bit redundant, though – could use a let instead: main = do let a = "hell" b = "yeah" putStrLn $ a ++ " " ++ b   Usually, you’ll use return to create I/O actions that don’t do anything (but you have to have one anyway, like an if-then-else), or for the last line of a do block, so it returns some value we want. 10

Takeaway: Return in haskell is NOT like other languages. main = do        line <- getLine       if null line           then return ()           else do               putStrLn $ reverseWords line               main      reverseWords :: String -> String   reverseWords = unwords . map reverse . words  Note: reverseWords = unwords . map reverse . words is the same as reverseWords st = nwords (map reverse (words st)) 11

print (works on any type in show, but calls show first) Other I/O functions: print (works on any type in show, but calls show first) putStr - And as putStrLn, but no newline putChar and getChar main = do  print True               print 2               print "haha"               print 3.2               print [3,4,3]  main = do          c <- getChar       if c /= ' '           then do               putChar c               main           else return ()   12

More advanced functionality is available in Control.Monad: import Control.Monad   import Data.Char      main = forever $ do       putStr "Give me some input: "       l <- getLine       putStrLn $ map toUpper l  (Will indefinitely ask for input and print it back out capitalized.) 13

sequence: takes list of I/O actions and does them one after the other Other functions: sequence: takes list of I/O actions and does them one after the other mapM: takes a function (which returns an I/O) and maps it over a list Others available in Control.Monad: when: takes boolean and I/O action. If bool is true, returns same I/O, and if false, does a return instead 14

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

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 16

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" 17

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] 18

Functors Functors are a typeclass, just like Ord, Eq, Show, and all the others. This one is designed to hold things that can be mapped over; for example, lists are part of this typeclass. class Functor f where       fmap :: (a -> b) -> f a -> f b This type is interesting - not like previous exmaples, like in EQ, where (==) :: (Eq a) => a -> a -> Bool. Here, f is NOT a concrete type, but a type constructor that takes one parameter. 19

fmap :: (a -> b) -> f a -> f b Compare fmap to map: fmap :: (a -> b) -> f a -> f b map :: (a -> b) -> [a] -> [b]    So map is a lot like a functor! Here, map takes a function and a list of type a, and returns a list of type b. In fact, can define map in terms of fmap: instance Functor [] where       fmap = map    20

instance Functor [] where fmap = map Notice what we wrote: instance Functor [] where       fmap = map    We did NOT write “instance Functor [a] where…”, since f has to be a type constructor that takes one type. Here, [a] is already a concrete type, while [] is a type constructor that takes one type and can produce many types, like [Int], [String], [[Int]], etc. 21

instance Functor Maybe where fmap f (Just x) = Just (f x) Another example: instance Functor Maybe where       fmap f (Just x) = Just (f x)       fmap f Nothing = Nothing    Again, we did NOT write “instance Functor (Maybe m) where…”, since functor wants a type constructor. Mentally replace the f’s with Maybe, so fmap acts like (a -> b) -> Maybe a -> Maybe b. If we put (Maybe m), would have (a -> b) -> (Maybe m) a -> (Maybe m) b, which looks wrong. 22

ghci> fmap (++ " HEY GUYS IM INSIDE THE Using it: ghci> fmap (++ " HEY GUYS IM INSIDE THE  JUST") (Just "Something serious.")   Just "Something serious. HEY GUYS IM INSIDE THE JUST"   JUST") Nothing   Nothing   ghci> fmap (*2) (Just 200)   Just 400   ghci> fmap (*2) Nothing   Nothing      23

Back to trees, as an example to put it all together: Let’s make a binary search tree type. Need comparisons to make sense, so want the type to be in Eq. Also going to have it be Show and Read, so anything in the tree can be converted to a string and printed (just to make displaying easier). data Tree a = EmptyTree | Node a (Tree a) (Tree a) deriving (Show,Read,Eq) 24

Note that this is slightly different than our last class. Node 5 (Node 3 (Node 1 EmptyTree EmptyTree) (Node 4 EmptyTree EmptyTree)) (Node 6 EmptyTree EmptyTree) This will let us code an insert that’s a bit easier to process, though! First step – a function to make a single node tree: singleton :: a -> Tree a   singleton x = Node x EmptyTree EmptyTree 25

Now – go code insert! treeInsert :: (Ord a) => a -> Tree a -> Tree a   treeInsert x EmptyTree =    treeInsert x (Node a left right)  =       26

My insert: treeInsert :: (Ord a) => a -> Tree a -> Tree a treeInsert x EmptyTree = singleton x   treeInsert x (Node a left right)        | x == a = Node x left right       | x < a  = Node a (treeInsert x left) right       | x > a  = Node a left (treeInsert x right)      27

Find: findInTree :: (Ord a) => a -> Tree a -> Bool   findInTree x EmptyTree = False   findInTree x (Node a left right)       | x == a = True       | x < a  = findInTree x left       | x > a  = findInTree x right     Note: If this is an “unordered” tree, would need to search both left and right subtrees. 28

ghci> let numsTree = foldr treeInsert EmptyTree nums An example run: ghci> let nums = [8,6,4,1,7,3,5]   ghci> let numsTree = foldr treeInsert EmptyTree nums   ghci> numsTree   Node 5 (Node 3 (Node 1 EmptyTree EmptyTree) (Node 4 EmptyTree EmptyTree)) (Node 7 (Node 6 EmptyTree EmptyTree) (Node 8 EmptyTree EmptyTree))    29

(a -> b) -> Tree a -> Tree b Back to functors: If we looked at fmap as though it were only for trees, it would look something like: (a -> b) -> Tree a -> Tree b We can certainly phrase this as a functor, also: instance Functor Tree where       fmap f EmptyTree = EmptyTree       fmap f (Node x leftsub rightsub) =  Node (f x) (fmap f leftsub)  (fmap f rightsub)    30

Using the tree functor: ghci> fmap (*2) EmptyTree   EmptyTree   ghci> fmap (*4) (foldr treeInsert  EmptyTree [5,7,3,2,1,7])   Node 28 (Node 4 EmptyTree (Node 8 EmptyTree (Node 12 EmptyTree (Node 20 EmptyTree EmptyTree)))) EmptyTree     31

System Level programming Scripting functionality deals with I/O as a necessity. The module System.Environment has several to help with this: getArgs: returns a list of the arguments that the program was run with getProgName: returns the string which is the program name (Note: I’ll be assuming you compile using “ghc –make myprogram” and then running “./myprogram”. But you could also do “runhaskell myprogram.hs”.) 32

An example: import System.Environment import Data.List main = do args <- getArgs progName <- getProgName putStrLn "The arguments are:" mapM putStrLn args putStrLn "The program name is:" putStrLn progName 33

$ ./arg-test first second w00t "multi word arg" The arguments are: The output: $ ./arg-test first second w00t "multi word arg" The arguments are: first second w00t multi word arg The program name is: arg-test 34