16-Nov-15 More Haskell Functions Maybe, Either, List, Set, Map.
Post on 05-Jan-2016
Embed Size (px)
*More Haskell FunctionsMaybe, Either, List, Set, Map
Maybefind takes a predicate and a list, and returns the first element that satisfies the predicateExample: find (> 4) [1..10]But what if there is no such element?find (> 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 -> Bool) -> [a] -> Maybe aA Maybe can have the value Nothing or Just somethingfind (>4) [1..10] Just 5find (> 40) [1..10] NothingThis works well when combined with pattern matching
EitherEither takes two types: Either a b buy :: String -> Int -> Either String Int buy item cost = if cost < 20 then Left ("Purchased " ++ item) else Right cost *Main> buy "lamp" 15 Left "Purchased lamp" *Main> buy "sofa" 300 Right 300
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
TypeclassesA Haskell typeclass is like a Java interface--it tells what functions an object can supportSome typeclasses and what they support:Eq -- == and /=Ord -- < = >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 -- >>= >> return fail
Data.List IThe standard Prelude imports many Data.List functions for us: map, filter, foldl, etc.intersperse :: a -> [a] -> [a]intersperse ' ' "hello" "h e l l ointercalate :: [a] -> [[a]] -> [a]intercalate " and " ["one", "two", "three"] "one and two and three"transpose :: [[a]] -> [[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"
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"
Data.Char Predicates:isControlisSpace (any whitespace)isLower, isUpperisAlpha, isAlphaNum, isDigitisPunctuationand othersConversions:toUpper, toLower, toTitledigitToInt, intToDigitord, chr
Data.Map Maps are constructed from lists of 2-tuplesNot using a Map:*Main> let nums = [(1, "one"), (2, "two"), (3, "three"), (4, "four"), (5, "five")]*Main> lookup 3 nums Just "three"Using a Map:*Main> let dict = Map.fromList nums*Main> dict fromList [(1,"one"),(2,"two"),(3,"three"),(4,"four"),(5,"five")]*Main> :t Map.fromList Map.fromList :: (Ord k) => [(k, a)] -> Map.Map k a*Main> Map.lookup 3 dict Just "three"*Main> Map.lookup 7 dict Nothing
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
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
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
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
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