ocaml

How to combine elements of a list into one element in Ocaml?


I am trying to combine a list of integers into one integer in Ocaml. For example, Input - List = [2,3,6,7,9] Desired Output - 97632.

I know how to iterate a list but what operation/function should I be using to get the desired output?


Solution

  • Any time you're converting a list into another value, you should be looking at using either List.fold_left or List.fold_right. It works the other way, but consider the below.

    # List.fold_left (fun i x -> i ^ string_of_int x) "" [1;2;3;4];;
    - : string = "1234"
    # 
    

    See the list fold function documentation.

    Alternatively, simply map the list of ints to a list of strings, and then use String.concat.

    # [1; 2; 3; 4]
      |> List.map string_of_int
      |> String.concat "";;
    - : string = "1234"
    

    And as an additional option, use Format.pp_print_list to print a list into a string without any separator.

    # Format.(
        let pp_sep _ () = () in
        [1; 2; 3; 4]
        |> asprintf "%a" (pp_print_list ~pp_sep pp_print_int)
      );;
    - : string = "1234"