Home > other >  Is there a more OCaml-esque way to convert a tuple list to list than what I did?
Is there a more OCaml-esque way to convert a tuple list to list than what I did?

Time:06-09

My goal here was to convert a (int * int) list to an int list. This is what I did:

let tuples_list_to_list l =
  let rec aux_tuples_to_list acc l =
    match l with
    | [] -> acc
    | x :: tl -> aux_tuples_to_list (fst x :: snd x :: acc) tl in
  aux_tuples_to_list [] l

I was wondering if there was a more "elegant" even though this is subjective or at least better, way to write my function. I was thinking about using List.map or List.fold_left but I was having issues figuring out I could use those two functions to do the same thing I did. Basically, I think it would be possible to have a one-liner instead of the whole function I wrote.

What do you think? Thanks

CodePudding user response:

This task is suited for List.concat_map (also known as "flat map" in some other languages):

(* List.concat_map : ('a -> 'b list) -> 'a list -> 'b list *)

let tuples_list_to_list l = List.concat_map (fun (x, y) -> [x; y]) l

You can use List.fold_left, but you'll have to reverse the result at the end as the list is constructed in reverse order:

let tuples_list_to_list l = List.rev (List.fold_left (fun acc (x, y) -> y :: x :: acc) [] l)
  • Related