Palindromic Number in OCaml

Published on 17 May 2026 (Updated: 17 May 2026)

Welcome to the Palindromic Number in OCaml page! Here, you'll find the source code for this program as well as a description of how the program works.

Current Solution

let ( let* ) = Option.bind

let palindrome str =
  let rec aux lo hi =
    lo >= hi || (str.[lo] = str.[hi] && (aux [@tailcall]) (lo + 1) (hi - 1))
  in
  aux 0 (String.length str - 1)

let validate_arg = function
  | [| _; n |] ->
      let* num = int_of_string_opt n in
      if num >= 0 then
        (* Converting back and forth normalizes the number 
           - allows for checking things like "+323" based on the actual numerical value *)
        (* Problem statement is underspecified, so going to follow Postel's law and be permissive :) *)
        Some (string_of_int num)
      else None
  | _ -> None

let () =
  match validate_arg Sys.argv with
  | Some n -> Printf.printf "%b\n" (palindrome n)
  | None -> print_endline "Usage: please input a non-negative integer"

Palindromic Number in OCaml was written by:

If you see anything you'd like to change or update, please consider contributing.

How to Implement the Solution

No 'How to Implement the Solution' section available. Please consider contributing.

How to Run the Solution

No 'How to Run the Solution' section available. Please consider contributing.