Longest Word in OCaml

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

Welcome to the Longest Word 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

(* Use custom function instead of Char.Ascii.is_white because the builtin also matches 
   on vertical tab and form feed which are not considered whitespace for the 
   purposes of this problem *)
let is_whitespace = function ' ' | '\t' | '\n' | '\r' -> true | _ -> false

let longest_word_len s =
  let best, _ =
    String.fold_left
      (fun (best, curr) c ->
        if is_whitespace c then (best, 0)
        else
          let curr = curr + 1 in
          (Int.max best curr, curr))
      (0, 0) s
  in
  best

let () =
  print_endline
  @@
  match Sys.argv with
  | [| _; s |] when s <> "" -> string_of_int (longest_word_len s)
  | _ -> "Usage: please provide a string"

Longest Word 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.