-
-
Save sylbru/4d7de9fac0f3f03c5fe8317ee19889b8 to your computer and use it in GitHub Desktop.
Get groups of repeated numbers from a number list (v2)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Main exposing (repeatedGroups) | |
-- Try this code at https://ellie-app.com/m72tn6Z8Sxra1 | |
repeatedGroups : List number -> List (List number) | |
repeatedGroups numbers = | |
let | |
processNumber : number -> List (List number) -> List (List number) | |
processNumber number groups = | |
case groups of | |
[] -> | |
[ [ number ] ] | |
((previousNumber :: _) as currentGroup) :: previousGroups -> | |
if number == previousNumber then | |
-- Continue current group | |
(number :: currentGroup) :: previousGroups | |
else | |
-- New group | |
[ number ] :: currentGroup :: previousGroups | |
[] :: _ -> | |
-- Shouldn’t happen: we always add non empty groups | |
groups | |
in | |
-- Fold over the list, starting from the right: our groups are added at the | |
-- beginning so we avoid a List.reverse at the end. The groups themselves | |
-- are made from the same element repeated, so the order inside doesn’t matter. | |
List.foldr processNumber [] numbers | |
-- Keep repeated groups only | |
|> List.filter (\group -> List.length group > 1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment