Int in OCaml

I teach myself OCaml, and the main resources that I use for practice are some of the problems that Cornell provided from its class 3110. One of the problems is to write a function to invert int (ie: 1234 β†’ 4321, -1234 β†’ -4321, 2 β†’ 2, -10 β†’ -1, etc.).

I have a working solution, but I am concerned that this is not a completely idiomatic OCaml:

let rev_int (i : int) : int = let rec power cnt value = if value / 10 = 0 then cnt else power (10 * cnt) (value/10) in let rec aux pow temp value = if value <> 0 then aux (pow/10) (temp + (value mod 10 * pow)) (value / 10) else temp in aux (power 1 i) 0 i 

It works correctly in all cases, as far as I can tell, but it seems to me that it looks "un-OCaml", especially because I run the length of the int twice with two internal functions. So I'm just wondering if there is an β€œOCaml” way to do this.

+5
source share
2 answers

I would say that the following is idiomatic enough.

 (* [rev x] returns such value [y] that its decimal representation is a reverse of decimal representation of [x], eg, [rev 12345 = 54321] *) let rev n = let rec loop acc n = if n = 0 then acc else loop (acc * 10 + n mod 10) (n / 10) in loop 0 n 

But, as Jeffrey said in a comment, your decision is rather idiomatic, although not the most pleasant.

By the way, my own style would be to write like this:

 let rev n = let rec loop acc = function | 0 -> acc | n -> loop (acc * 10 + n mod 10) (n / 10) in loop 0 n 

As I prefer pattern matching with if/then/else . But this is a matter of my personal taste.

+4
source

I can offer you some way to do this:

 let decompose_int i = let r = i / 10 in i - (r * 10) , r 

This function allows me to decompose an integer as if I had a list. For example, 1234 divided into 4 and 123 . Then we will cancel it.

 let rec rev_int i = match decompose_int i with | x , 0 -> 10 , x | h , t -> let (m,r) = rev_int t in (10 * m, h * m + r) 

The idea here is to return 10 , 100 , 1000 ... etc. to find out where to place the last digit.


What I wanted to do here was to process them, since I will be considering lists, decompose_int is the equivalent of List.hd and List.tl

+1
source

All Articles