Chapter 7: Modules

Learn You a Haskell for Great Good!

Loading modules

  • Modules is a collection of related functions, types and typeclasses.
  • Prelude module is imported by default.
import <module name>
  • nub is a function defined in Data.List that take a list and weeds out duplicate elements.
  • The following are equivalent
length.nub
\xs -> length (nub xs)
  • To import module in GHCI (interpreter), use
:m + Data.List Data.Map Data.set
  • To use, or hide a specific function.
import Data.List (nub, sort)
import Data.List hiding (nub)
  • To resolve conflict in namespace, use qualified to ensure that import module still need to use the module name to call each function such as
import qualified Data.Map
Data.Map.filter
import qualified Data.Map as M
M.filter

Data.List

  • Data.List module contain function about List.
  • intersperse take an element and a list and then puts that element in between each pair of element in the list.
intersperse '.' "MONKEY"
"M.O.N.K.E.Y"
  • intercalate takes a list of lists and a list and inserts the list in between the list of lists and flatten the list of lists.
intercalate [0,0] [[1,2],[3,4],[5,6]]
[1,2,0,0,3,4,0,0,5,6]
  • transpose transposes a list of lists like a 2D matrix.
  • concat flatten a list of lists into a list of elements.
  • The following are equivalent
concat (map (replicate 4) [1..3])
concatMap (replicate 4) [1..]
  • and, or follow the predicate logic
  • any and all take a predicate and then check if any or all the elements in a list satisfy the predicate.
  • iterate take a function and a starting value and applies the function to the starting value and then apply the function to the result and use the result as new starting value
take 10 $ iterate (*2) 1
[1,2,4,8,16,32,64,128,256,512]
  • splitAt takes a number and a list. it split the list at the element corresponding to the position of the number.
  • takeWhile takes elements from a list while the predicate holds and then when an element is encountered that does satisfy the predicate, it cuts off.
  • dropWhile is opposite of takeWhile
  • span return a pair of lists where the first list is the same if use takeWhile and the second list is what would’ve dropped.
  • break p is the equivalent of doing span(not.p)
splitAt 3 "heyman"
("hey","man")
takeWhile (>3) [6,5,4,3,2,1,2,3,4,5,4,3,2,1]
[6,5,4]
dropWhile (>3) [6,5,4,3,2,1,2,3,4,5,4,3,2,1]
[3,2,1,2,3,4,5,4,3,2,1]
span (>3) [6,5,4,3,2,1,2,3,4,5,4,3,2,1]
[[6,5,4],[3,2,1,2,3,4,5,4,3,2,1]]
  • sort will sorts a list
  • group will group adjacent elements into sublist if they are equal
  • inits and tails are init and tail but recursively apply to create a list
  • isInfixOf, isPrefixOf and isSuffixOf search for a sublist within, begin or end of a list, respectively.
  • elem and notElem check if an element is or not inside a list
  • partition takes a list and a predicate and return a pair of lists where the first contain element satisfy the predicate and the other list don’t.
inits "w00t"
["", "w", "w0", "w00", "w00t"]
partition (>3) [1,3,5,6,3,2,1,0,3,7]
([5,6,7],[1,3,3,2,1,0,3])
  • Maybe type can return one or nothing.
  • find takes a list and a predicate and returns the first element that satisfy the predicate. It can return one element or nothing.
  • elemIndex return either nothing or the position of the first element found.
  • elemIndices is like elemIndex but return all matching indices.
  • findIndex is like find but return the first index of the matching element. findIndices return all indices of the matching element.
  • zip and zipWith can zip together x list when using zipx and zipWithx (e.g. zip4 and zipWith4) up to x =7.
  • line takes a string and return every line of that string in a separate list
  • unlines is the inverse function of lines
  • word and unwords splitting a line of text into words or reverse the process.
  • nub take a list and take out any duplicate
  • delete take a list and an element and remove the first matching element in the list
  • \\ is a list diff function. Return a list only with different element between the lists
  • union and intersect acts exactly like set operator
  • insert take an element and a list and search for the first position that the element is smaller or equal to the next element and insert itself into that position.
insert 3 [1,2,4,3,2,1]
[1,2,3,4,3,2,1]
  • Note that length, take, drop, splitAt, !!, replicate take Int type. add generic in front to take Num type (e.g. genericSplitAt instead of splitAt)
  • nub, delete, union, intersect, group, sort, insert, maximum and minimum counterpart is add By at the end (e.g. nubBy)
  • example of using on (Data.Function), notice the first 3 negative grouped together, then the next 6 positive number, next 2 negative and finally next 2 positive values.
let value =  [-4.3, -2.4, -1.20.42.35.910.529.15.3, -2.4, -14.52.92.3]
groupBy ((==) `on` (> 0)) values
[[-4.3,-2.4,-1.2],[0.4,2.3,5.9,10.5,29.1,5.3],[-2.4,-14.5],[2.9,2.3]]  
let xs = [[5,4,5,4,4],[1,2,3],[3,5,4,3],[],[2],[2,2]]  
sortBy (compare `on` length) xs
[[],[2],[2,2],[1,2,3],[3,5,4,3],[5,4,5,4,4]]

Data.Char

  • Data.Char functions work with characters.
  • isControl checks whether a character is a control character (??)
  • isSpace, isLower, isUpper, isAlpha, isAlphaNum, isDigit, isOctDigit, isHexDigit, isLetter, isMark (unicode), isNumber, isPunctuation, isSymbol, isSeparator, isAscii, isLatin1, isAsciiUpper and isAsciiLower are self explained
  • toUpper, toLower, toTitle (title case), digitToInt and intToDigit are self explanatory as well.
  • isPrint check whether a character is printable
  • all take a predicate and a list and return True if that predicate holds for every elements in the list
all isAlphaNum "bobby283"
True
  • ord and chr convert the character to the encoding number

Data.Map

  • Data.Map function work with key-value pair list.
  • findKey takes a key and a list and filter out all non-matching key pair and first matching key-value pair.
  • fromList take an association list and return a map with the same association. The duplicate keys in the original association list are discarded. The key must be orderable.
Map.fromList [(1,2),(3,4),(3,2),(5,5)]
fromList [(1,2),(3,2),(5,5)]
  • empty represents an empty map.
  • insert takes a key, a value and a map and return a new map with those inserted into the map.
fromList' :: (Ord k) => [(k,v)] -> Map.Map k v
fromList' = foldr (\(k,v) acc -> Map.insert k v acc) Map.empty
  • null checks if a map is empty
  • size reports the size of a map
  • singleton create one mapping of a key to a value
  • lookuup returns Just something if it finds something or Nothing if not.
  • member is a predicate of whether a key and a value is in the map
  • map & filter works like list equivalents
  • toList is the inverse of fromList
  • keys and elems return list of the keys or the values, respectively.
  • fromListWith is like fromList but doesn’t discard duplicate but use the function to find out what to do with it. E.g. max (fromListWith max …) will retain the maximum value of the duplicate key.
  • insertWith is to insert what fromListWith is to fromList.

Data.Set

  • Data.Set work with set using set operators.
  • fromList functions takes a list and convert it into a set.
  • intersection, difference, union set operators work exactly like they should.
  • So is null, size, member, empty, singleton, insert and delete.
  • map and filter, toList functions also work as expected.
Set.filter odd $ Set.fromList [3,4,5,6,7,2,3,4]
fromList[3,5,7]
Set.map (+1) $ Set.fromList [3,4,5,6,7,2,3,4]
fromList [3,4,5,6,7,8]

Making our own modules

  • To make your own modules
    • create a file with a new module name (e.g. Geometry.hs)
    • Specify module name and functions at the top
    • implement each function below it
    • to use the module, use import but the module file must be in the same folder.
module Geometry
( sphereVolume
, sphereArea
, cubeVolume
, cubeArea
, cuboidArea
, cuboidVolumne
) where

sphereVolume :: Float -> Float
sphereVolume radius = (4.0 / 3.0) * pi * (radius ^ 3)
...

Other commands

  • additional explanation of fold here.
foldr (\x y -> concat ["(",x,"+",y,")"]) "0" (map show [1..5])
"(1+(2+(3+(4+(5+0)))))"
foldl (\x y -> concat ["(",x,"+",y,")"]) "0" (map show [1..5])
"(((((0+1)+2)+3)+4)+5)
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s