Haskell: Exercise #9
This commit is contained in:
		
							parent
							
								
									ceed59bf21
								
							
						
					
					
						commit
						f4496a8648
					
				
							
								
								
									
										44
									
								
								Haskell.org
									
									
									
									
									
								
							
							
						
						
									
										44
									
								
								Haskell.org
									
									
									
									
									
								
							| @ -195,3 +195,47 @@ import Data.List | ||||
| compress :: Eq a => [a] -> [a] | ||||
| compress = map head . group | ||||
| #+end_src | ||||
| *** #9 Pack consecutive duplicates of list elements into sublists | ||||
| 
 | ||||
| If a list contains repeated elements they should be placed in separate sublists. | ||||
| 
 | ||||
| Example: | ||||
| 
 | ||||
| #+begin_src haskell | ||||
| ,* (pack '(a a a a b c c a a d e e e e)) | ||||
| ((A A A A) (B) (C C) (A A) (D) (E E E E)) | ||||
| #+end_src | ||||
| 
 | ||||
| Example in Haskell: | ||||
| 
 | ||||
| #+begin_src haskell | ||||
| λ> pack ['a', 'a', 'a', 'a', 'b', 'c', 'c', 'a', 'a', 'd', 'e', 'e', 'e', 'e'] | ||||
| ["aaaa","b","cc","aa","d","eeee"] | ||||
| #+end_src | ||||
| **** Solution | ||||
| In python you can use ~Counter~ | ||||
| #+begin_src python | ||||
| from collections import Counter | ||||
| def pack(arr): | ||||
|     return [[key] * val for key,val in Counter(arr).items()] | ||||
| #+end_src | ||||
| 
 | ||||
| In Haskell, this is just ~group~ | ||||
| 
 | ||||
| #+begin_src haskell | ||||
| pack :: [a] -> [[a]] | ||||
| pack = group | ||||
| #+end_src | ||||
| 
 | ||||
| Here's my naive implementation | ||||
| 
 | ||||
| #+begin_src haskell | ||||
| pack :: Eq a => [a] -> [[a]] | ||||
| pack xs = reverse $ go [[]] xs | ||||
|   where | ||||
|     go acc [] = acc | ||||
|     go ([]:acc) (x:xs) = go ([x]:acc) xs | ||||
|     go ((a:as):acc) (x:xs) | ||||
|        | a == x = go ((x:a:as):acc) xs | ||||
|        | otherwise = go ([x]:(a:as):acc) xs | ||||
| #+end_src | ||||
|  | ||||
		Loading…
	
	
			
			x
			
			
		
	
		Reference in New Issue
	
	Block a user