Grouping consecutive integers in F# and Haskell
Let's look at what F# and Haskell can offer us while reimplementing grouping consecutive integers in C# algorithm.
F#:
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
let groupConsecutive xs = | |
List.foldBack (fun x acc -> | |
match acc, x with | |
| [], _ -> [[x]] | |
| (h :: t) :: rest, x when h - x <= 1 -> (x :: h :: t) :: rest | |
| acc, x -> [x] :: acc) xs [] | |
[1; 2; 4; 5; 6; 9] |> groupConsecutive |
Haskell:
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
groupConsecutive :: (Ord a, Num a) => [a] -> [[a]] | |
groupConsecutive = foldr group [] | |
where | |
group x [] = [[x]] | |
group x acc@((h:t):rest) | |
| h - x <= 1 = (x:h:t):rest | |
| otherwise = [x]:acc | |
main :: IO() | |
main = print $ groupConsecutive [1, 2, 4, 5, 6, 9 :: Int] |
For my current taste, the Haskell version is more readable due to the awesome separate type annotation and to the lovely Erlang-style pattern matching on function arguments.
Comments