programming in haskell
Post on 26-Jan-2016
Embed Size (px)
DESCRIPTIONPROGRAMMING IN HASKELL. I/O and functors. Based on lecture notes by Graham Hutton The book Learn You a Haskell for Great Good (and a few other sources). File I/O. - PowerPoint PPT Presentation
*PROGRAMMING IN HASKELLBased on lecture notes by Graham HuttonThe book Learn You a Haskell for Great Good (and a few other sources)I/O and functors
*File I/OSo far, weve 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"$ghc--makehelloworld[1of1]CompilingMain(helloworld.hs,helloworld.o)Linkinghelloworld...$./helloworldhello,worldNow we actually compile a program:
*What are these functions? ghci>:tputStrLnputStrLn::String->IO()ghci>:tputStrLn"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.
*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=doputStrLn"Hello,what'syourname?name
*More on getLine: ghci>:tgetLinegetLine::IOStringThis is the first I/O weve seen that doesnt have an empty tuple type - it has a String.
Once the string is returned, we use the
*An invalid example: nameTag="Hello,mynameis"++getLineWhats 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
*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 cant be bound to a name, since that is the one that is the return type).At the ghci prompt:ghci>putStrLn"HEEY"HEEY
*You can use let statements inside do blocks, to call other functions (and with no in part required):importData.Char
*Return in haskell: NOT like other languages.main=dolineStringreverseWords=unwords. mapreverse.wordsNote: reverseWords = unwords . map reverse . words is the same as reverseWords st = nwords (map reverse (words st))
*What is return?
Does NOT signal the end of execution! Return instead makes an I/O action out of a pure value. main=doa
*Last example was a bit redundant, though could use a let instead:main = do let a = "hell" b = "yeah" putStrLn $ a ++ " " ++ b Usually, youll use return to create I/O actions that dont 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.
- *Other I/O functions: print (works on any type in show, but calls show first)putStr - And as putStrLn, but no newlineputChar and getCharmain=doprintTrueprint2print"haha"print3.2print[3,4,3]main=doc
- *More advanced functionality is available in Control.Monad:importControl.MonadimportData.Charmain=forever$doputStr"Givemesomeinput:"l
*Other functions:sequence: takes list of I/O actions and does them one after the othermapM: 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
*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 withgetProgName: returns the string which is the program name System Level programming(Note: Ill be assuming you compile using ghc make myprogram and then running ./myprogram.But you could also do runhaskell myprogram.hs.)
- *import System.Environment import Data.List main = do args
*$ ./arg-test first second w00t "multi word arg" The arguments are: first second w00t multi word arg The program name is: arg-test The output:
*Recap of TypeclassesWe 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)
*Now say we want to make a new type and make sure it belongs to a given typeclass. Heres how:data TrafficLight = Red | Yellow | Green
instance Eq TrafficLight where Red == Red = True Green == Green = True Yellow == Yellow = True _ == _ = False
*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 hadnt added trees to this class!)instance Show TrafficLight where show Red = "Red light" show Yellow = "Yellow light" show Green = "Green light"
*And finally, we can use these things:ghci> Red == Red True ghci> Red == Yellow False ghci> Red `elem` [Red, Yellow, Green] True ghci> [Red, Yellow, Green] [Red light,Yellow light,Green light]
*FunctorsFunctors 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.classFunctorfwherefmap::(a->b)->fa->fbThis 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.
*Compare fmap to map: fmap::(a->b)->fa->fbmap :: (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:instanceFunctorwherefmap=map
*Notice what we wrote: instanceFunctorwherefmap=mapWe 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.
*Another example: instanceFunctorMaybewherefmapf(Justx)=Just(fx)fmapfNothing=NothingAgain, we did NOT write instance Functor (Maybe m) where, since functor wants a type constructor.
Mentally replace the fs 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.
*Using it: ghci>fmap(++"HEYGUYSIMINSIDETHE JUST")(Just"Somethingserious.")Just"Somethingserious.HEYGUYSIMINSIDETHEJUST"ghci>fmap(++"HEYGUYSIMINSIDETHE JUST")NothingNothingghci>fmap(*2)(Just200)Just400ghci>fmap(*2)NothingNothing
*Back to trees, as an example to put it all together:
Lets 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)
*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 thats a bit easier to process, though!
First step a function to make a single node tree:singleton::a->Treeasingletonx=NodexEmptyTreeEmptyTree
*Now go code insert!
findInTree::(Orda)=>a->Treea->BoolfindInTreexEmptyTree=FalsefindInTreex(Nodealeftright)|x==a=True|xa=findInTreexrightNote: If this is an unordered tree, would need to search both left and right subtrees.
*An example run:ghci>letnums=[8,6,4,1,7,3,5]ghci>letnumsTree=foldrtreeInsertEmptyTreenumsghci>numsTreeNode5(Node3(Node1EmptyTreeEmptyTree)(Node4EmptyTreeEmptyTree))(Node7(Node6EmptyTreeEmptyTree)(Node8EmptyTreeEmptyTree))
*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:instanceFunctorTreewherefmapfEmptyTree=EmptyTreefmapf(Nodexleftsubrightsub)= Node(fx)(fmapfleftsub) (fmapfrightsub)
*Using the tree functor:ghci>fmap(*2)EmptyTreeEmptyTreeghci>fmap(*4)(foldrtreeInsertEmptyTree[5,7,3,2,1,7])