Search code examples
integerocamldigits

ocaml looking at a specific digit of an int


I am writing an ocaml program and I can't figure out how to look at specific digits of an int

so say for example we have

let a = 405;;

I want to be able to look at the first digit, 4, or the second one, 0. How can I accomplish this? I was thinking of turning it into a string and looking at the chars, but I feel like there should be another way of doing it.


Solution

  • You can write a recursive function to extract all digits from a number:

    (* Assuming n is a non-negative number *)
    let digits n =
        let rec loop n acc =
            if n = 0 then acc
            else loop (n/10) (n mod 10::acc) in
        match n with
        | 0 -> [0]
        | _ -> loop n []
    

    Once you have a list of digits

    # digits 405;;
    - : int list = [4; 0; 5]
    

    you can get any digit by using some List functions.