16-Nov-15 More Haskell Functions Maybe, Either, List, Set, Map

Download 16-Nov-15 More Haskell Functions Maybe, Either, List, Set, Map

Post on 05-Jan-2016




4 download

Embed Size (px)


<ul><li><p>*More Haskell FunctionsMaybe, Either, List, Set, Map</p></li><li><p>Maybefind takes a predicate and a list, and returns the first element that satisfies the predicateExample: find (&gt; 4) [1..10]But what if there is no such element?find (&gt; 40) [1..10]In such a case, Java would return nullTheres nothing in the syntax that warns you this might happenThus, you can get a NullPointerExceptionIn Haskell, find returns a Maybefind :: (a -&gt; Bool) -&gt; [a] -&gt; Maybe aA Maybe can have the value Nothing or Just somethingfind (&gt;4) [1..10] Just 5find (&gt; 40) [1..10] NothingThis works well when combined with pattern matching</p></li><li><p>EitherEither takes two types: Either a b buy :: String -&gt; Int -&gt; Either String Int buy item cost = if cost &lt; 20 then Left ("Purchased " ++ item) else Right cost *Main&gt; buy "lamp" 15 Left "Purchased lamp" *Main&gt; buy "sofa" 300 Right 300</p></li><li><p>ModulesA Haskell module is like a Java packageA module contains functions, types, and typeclassesUnlike Java, there are a lot of name collisions, so modules often have to be imported in a qualified wayTo import into GHCi, use :m + module ... moduleTo import into a program, use import moduleimport module (f1,...,fn) will import only the named functionsimport module hiding (f1,...,fn) will import all but the named functionsimport qualified module imports the module; we call an imported function fn with module.fnimport qualified module as M imports the module; we call an imported function fn with M.fn</p></li><li><p>TypeclassesA Haskell typeclass is like a Java interface--it tells what functions an object can supportSome typeclasses and what they support:Eq -- == and /=Ord -- &lt; = &gt;Num -- + - * / and othersShow -- show (enables printing as a string)Read -- read (conversion from a string to something else)Functor -- fmap (enables mapping over things)Lists belong to the Functor typeclassMonad -- &gt;&gt;= &gt;&gt; return fail</p></li><li><p>Data.List IThe standard Prelude imports many Data.List functions for us: map, filter, foldl, etc.intersperse :: a -&gt; [a] -&gt; [a]intersperse ' ' "hello" "h e l l ointercalate :: [a] -&gt; [[a]] -&gt; [a]intercalate " and " ["one", "two", "three"] "one and two and three"transpose :: [[a]] -&gt; [[a]]transpose [[1,2,3],[4,5,6]] [[1,4],[2,5],[3,6]]take 5 (iterate (* 2) 1) [1,2,4,8,16]take 5 (drop 5 (iterate (* 2) 1)) [32,64,128,256,512]take 5 $ drop 5 $ iterate (* 2) 1 [32,64,128,256,512]takeWhile (/= ' ') "Hello there" "HellodropWhile (/= ' ') "Hello there" " there"</p></li><li><p>Data.List IIThe following are especially helpful when dealing with text: span isLetter "one two three" ("one"," two three")break isSpace "one two three" ("one"," two three")words "Here are some words." ["Here","are","some","words."]unwords $ words "Here are some words." "Here are some words."lines "Roses are red\nViolets are blue" ["Roses are red","Violets are blue"]unlines $ lines "Roses are red\nViolets are blue" "Roses are red\nViolets are blue\n"</p></li><li><p>Data.Char Predicates:isControlisSpace (any whitespace)isLower, isUpperisAlpha, isAlphaNum, isDigitisPunctuationand othersConversions:toUpper, toLower, toTitledigitToInt, intToDigitord, chr</p></li><li><p>Data.Map Maps are constructed from lists of 2-tuplesNot using a Map:*Main&gt; let nums = [(1, "one"), (2, "two"), (3, "three"), (4, "four"), (5, "five")]*Main&gt; lookup 3 nums Just "three"Using a Map:*Main&gt; let dict = Map.fromList nums*Main&gt; dict fromList [(1,"one"),(2,"two"),(3,"three"),(4,"four"),(5,"five")]*Main&gt; :t Map.fromList Map.fromList :: (Ord k) =&gt; [(k, a)] -&gt; Map.Map k a*Main&gt; Map.lookup 3 dict Just "three"*Main&gt; Map.lookup 7 dict Nothing</p></li><li><p>Map operations IMaps in Haskell are implemented with binary trees, not with hash tablesHence, keys must belong to the Ord typeclass Map.empty -- returns an empty mapMap.null map -- tests if a map is emptyMap.singleton key value -- returns a map with one key/value pairMap.fromList list -- given a list of 2-tuples, returns a mapNote: Only the last value is kept if a key is repeatedMap.insert key value map -- inserts a key/value pairMap.size map -- returns the number of key/value pairsMap.member key -- tests if the key is in the mapMap.lookup key -- returns Just value or Nothing</p></li><li><p>Map operations IIMap.map f map -- returns a map in which f has been applied to each valueMap.filter f map -- returns a map containing only those key/value pairs for which f value is TrueMap.keys map -- returns a list of keysMap.elems map -- returns a list of valuesMap.toList map -- returns a list of (key, value) 2-tuplesMap.fromListWith f list -- given a list of 2-tuples, returns a map; f is applied to combine duplicate values for the same keyMap.insertWith f key value -- inserts the key/value pair into the map, using the function f to combine duplicate values for the same key</p></li><li><p>Sets in HaskellSets, like Maps, are constructed from listsLike Maps, the import should be qualified to avoid name collisions: import qualified Data.Set as Set Set.fromList list -- returns a set created from a list (duplicates are removed)Set.toList set -- returns an ordered list from a set</p></li><li><p>Set operationsSet.emptySet.null setSet.member value setSet.union set1 set2 Set.intersection set1 set2 Set.difference set1 set2Set.size setSet.singleton valueSet.insert value setSet.delete value setSet.map f setSet.filter f set </p></li><li><p>Compiling a Haskell programOn UNIX (including Linux and Mac OS):Compile with ghc --make filename (omit the .hs)Run with ./filename On Windows:Set the PATH environment variable to something like C:\ghc\ghc-6.6\binCompile with ghc inputfile -o outputfileAlso works on a Maccompiling hello.hs results in hello.hi, hello.o, and main.exeRun with outputfile.exe Running as an interpreted program, without compiling:runhaskell filename.hs</p></li><li><p>The End</p><p>***************</p></li></ul>