Haskell n.8
This commit is contained in:
parent
c54a056489
commit
ceed59bf21
47
Haskell.org
47
Haskell.org
@ -148,3 +148,50 @@ flatten = reverse . go []
|
|||||||
go acc (Elem x) = x:acc
|
go acc (Elem x) = x:acc
|
||||||
go acc (List (x:xs)) = go (go acc x) (List xs)
|
go acc (List (x:xs)) = go (go acc x) (List xs)
|
||||||
#+end_src
|
#+end_src
|
||||||
|
*** #8 Eliminate consecutive duplicates of list elements
|
||||||
|
|
||||||
|
If a list contains repeated elements they should be replaced with a single copy of the element. The order of the elements should not be changed.
|
||||||
|
|
||||||
|
Example:
|
||||||
|
|
||||||
|
#+begin_src haskell
|
||||||
|
,* (compress '(a a a a b c c a a d e e e e))
|
||||||
|
(A B C A D E)
|
||||||
|
#+end_src
|
||||||
|
|
||||||
|
Example in Haskell:
|
||||||
|
|
||||||
|
#+begin_src haskell
|
||||||
|
λ> compress "aaaabccaadeeee"
|
||||||
|
"abcade"
|
||||||
|
#+end_src
|
||||||
|
**** Solution
|
||||||
|
|
||||||
|
This is not great...
|
||||||
|
|
||||||
|
#+begin_src haskell
|
||||||
|
compress xs = reverse $ go [] xs
|
||||||
|
where go acc [] = acc
|
||||||
|
go [] (x:xs) = go [x] xs
|
||||||
|
go [a] [x]
|
||||||
|
| a == x = [a]
|
||||||
|
| otherwise = [x,a]
|
||||||
|
go (a:as) [x]
|
||||||
|
| a == x = a:as
|
||||||
|
| otherwise = x:a:as
|
||||||
|
go [a] (x:xs)
|
||||||
|
| a == x = go [a] xs
|
||||||
|
| otherwise = go [x,a] xs
|
||||||
|
go (a:as) (x:xs)
|
||||||
|
| a == x = go (a:as) xs
|
||||||
|
| otherwise = go (x:a:as) xs
|
||||||
|
#+end_src
|
||||||
|
|
||||||
|
Especially when one of the solutions is the following;
|
||||||
|
|
||||||
|
#+begin_src haskell
|
||||||
|
import Data.List
|
||||||
|
|
||||||
|
compress :: Eq a => [a] -> [a]
|
||||||
|
compress = map head . group
|
||||||
|
#+end_src
|
||||||
|
Loading…
x
Reference in New Issue
Block a user