filiard
filiard

Reputation: 501

How to print list as int in OCaml?

Say I have any list, for example

let lista = [1;2;3;4;5;6]

How do I write this as

int = 123456

so that i can later pass it to a function?

I tried

  let rec print lista =
  match lista with
  []->()
  |a::lista ->print_int a; print lista;;

but i dont get expected result, only

 - : unit = ()

I know about int_of_string, so whether my function returns string or int doesnt really matter.

Upvotes: 0

Views: 1521

Answers (2)

Aldrik
Aldrik

Reputation: 136

A possible solution :

lista 
|> List.fold_left (fun a x -> a * 10 + x) 0;;

the accumulator is multiplied by 10 and we add the current element of the list

the second parameter for initializing the accumulator to 0.

List.fold_left is very useful for processing a list.

If you need to print the result modify the code adding the line to print directly the result :

lista 
|> List.fold_left (fun a x -> a * 10 + x) 0
|> print_int;;

Upvotes: 2

gallais
gallais

Reputation: 12103

You're quite close to a solution: instead of printing the solution to the standard output, you should produce a string for each number and append them together. Here are functions you will need:

val string_of_int : int -> string

and

val (^) : string -> string -> string

Alternatively, you could bypass int_of_string and implement a direct solution by noticing that:

to_int [a; b; ...; c; d] = ab...cd
                         = d + 10 * (c + 10 * (... + 10 * (b + 10 * c)))

i.e. that this has a neat recursive structure.

Upvotes: 1

Related Questions