7. Data.List
Welcome to the Stone Age, where we forget all tools and write functions using recursion, pattern matching, guards and conditionals.
For each of the following functions, write two check-expects (examples) and then write the function.
Group A: Useful Daily
-
myIntersperse
: takes in an element and a list, and puts the element between every pair of the list.myIntersperse 6 [1,2,9,10] == [1,6,2,6,9,6,10]
-
myIntercalate
: like intersperse, but for lists. Takes a list and a list of lists, and puts the first list in between each pair of lists from the second input. It “flattens” (concatenates) the result, removing one level of list. Note:String
is[Char]
, so this applies to putting strings in between a list of words.myIntercalate "_GO_" ["Speed","Racer","Car"] == "Speed_GO_Racer_GO_Car"
Group B
-
myAnd
takes a list of booleans and returns True only when they are all True. In the empty list, “all” of the entries are True. (Try to find one that isn’t!) -
myOr
takes a list of booleans and returns True if any item in the list is True. In the empty list, there aren’t any items that are True. -
myAll
takes two arguments: a function that produces a boolean, and a list of items. It gives True if applying the function to every item in the list results in a list with all entries True. -
myAny
: just likemyAll
but it gives True if any result is True. -
myConcat
takes a list of lists and concatenates them together (removing one level of nesting).myConcat [['b','i','r','d'],[' '],['d','o','g']] == ['b','i','r','d',' ','d','o','g']
-
myIterate :: (a->a) -> a -> [a]
takes in a functionf
and an itemx
, and returns an infinite list created by repeatedly applyingf
:[x, f x, f (f x), f (f (f x)), ...]
-
myConcatMap
applies a function to items in a list and then concatenates all of the results.
Group C
Making groups. We are going to continue to write “my” versions of all of these. Consult Chapter 7 in the book for examples of each of these.
splitAt
myTakeWhile
myDropWhile
span
break
(skip 2023)partition
(skip 2023)
Group D
We are going to write “my” versions of all of these.
find
elemIndex
(this is not the primary way to find something!!)elemIndices
(skip 2023)findIndex
(skip 2023)findIndices
(skip 2023)- Concisely state a similarity and a difference between
elemIndices
andfindIndices
. (skip 2023)
More
- Read the paragraph about “generic equivalents” that appears after
insert
and before the “deleteBy” paragraph.
Rules for the Stone Age
Encouraged
- patterns
- recursion
- list comprehensions
Discouraged Functions
- guards are OK but there are usually better ways
Banned Functions
- fold
- length
- head, tail
- fst, snd
- map
- elem
- elemIndices (yikes!!)
- if-then-else (there are clearer ways to write choices)
- concat (until you write it)
- concatMap (!!)