Hello,
I’m a complete greeny, just started learning my first functional language. I did Pack Consecutive Duplicates exercise in a quite different way than the proposed solution.
Proposed solution:
let pack list =
let rec aux current acc = function
| [] -> [] (* Can only be reached if original list is empty *)
| [x] -> (x :: current) :: acc
| a :: (b :: _ as t) ->
if a = b then aux (a :: current) acc t
else aux [] ((a :: current) :: acc) t in
List.rev (aux [] [] list)
Vs. what I came up:
let pack lst =
let rec pack_aux acc = function
| a :: (b :: _ as tl) ->
if a = b then pack_aux (b :: acc) tl
else acc :: pack_aux [b] tl
| _ -> [ acc ]
in
match lst with
| [] -> []
| a :: _ -> pack_aux [a] lst
Expected result:
# pack ["a"; "a"; "a"; "a"; "b"; "c"; "c"; "a"; "a"; "d"; "d"; "e"; "e"; "e"; "e"];;
- : string list list =
[["a"; "a"; "a"; "a"]; ["b"]; ["c"; "c"]; ["a"; "a"]; ["d"; "d"];
["e"; "e"; "e"; "e"]]
Both solutions produce the same results, but I’d like to know:
- Does my solution fit in ‘functional’ approach to the problem? (In terms of multi year influence of procedural languages on my mind)
- Do I miss something in the proposed solution in terms of better design? IDK, maybe some hidden copies or the lack of tail call optimisation in my proposal?