Reputation: 2914
https://wiki.haskell.org/99_questions/1_to_10
regarding the solution to Question 9
pack :: Eq a => [a] -> [[a]] -- problem 9
pack [] = []
pack (x:xs) = (x:first) : pack rest
where
getReps [] = ([], [])
getReps (y:ys)
| y == x = let (f,r) = getReps ys in (y:f, r)
| otherwise = ([], (y:ys))
(first,rest) = getReps xs
--input
pack ['a', 'a', 'a', 'a', 'b', 'c', 'c', 'a','a', 'd', 'e', 'e', 'e', 'e']
--output
["aaaa","b","cc","aa","d","eeee"]
whats going on here: (x:first)
, i can see that rest
is being passed pack
, but i don't understand the bit before that.
Upvotes: 0
Views: 65
Reputation: 532408
getReps
is a function specific to each iteration of pack
, as it closes over the current values of x
and xs
.
The first call to pack "aaaabccaadeeee"
results in a call to getReps "aaabccaadeeee"
. getReps
will return ("aaa", "bccaadeeee")
. Effectively, pack
self splits off the first 'a'
(the value of x
), and getReps
separates the rest of the 'a'
s from the value of xs
. Thus, the final "value" of pack "aaaabccaadeeee"
is ('a':"aaa") : pack "bccaadeeee"
.
Upvotes: 2