Reversing an integer in F#

Viewed 148

I'm trying to reverse an integer in F#. I have the following approach:

//let the number be n
rev = 0
while(n != 0){
    rev = rev * 10 + n % 10;
    n /= 10;
}
// rev now contains the reverse integer of n

I'm new to F#, and I don't know the the idiomatic syntax to achieve this implementation. I don't want to reverse the number by converting it to string first. How can this implementation be done in F# in an idiomatic way?

2 Answers

Create a recursive inner function that you call like so.

 let reverse n =
     let rec revInner n rev =
         match n with
         | 0 -> rev
         | _ -> revInner (n / 10) (rev * 10 + n % 10)
     revInner n 0

reverse 43221 // -> 12234

Whenever you have imperative loops such as a while look to convert it to a recursive function. In this case you need an inner function that is recursively called. The first pattern match deals with the termination condition of the while, the second deals with the core whileexecution:

  let revNum number =
    let rec loop rev = function
    | 0 -> rev
    | fwd ->  loop (rev*10 + fwd%10) (fwd/10)
    loop 0 number;;
Related