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#:

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:

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

Popular posts from this blog

Regular expressions: Rust vs F# vs Scala

Hash maps: Rust, F#, D, Go, Scala

Haskell: performance