John
John

Reputation: 23

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?

Upvotes: 0

Views: 283

Answers (1)

Chris
Chris

Reputation: 36680

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
    let pp_int ppf i = fprintf ppf "%d" i in
    [1; 2; 3; 4]
    |> asprintf "%a" (pp_print_list ~pp_sep pp_int)
  );;
- : string = "1234"

Upvotes: 2

Related Questions