Skip to content

Commit 6106c2c

Browse files
authored
Add Longest Word in OCaml (#6054)
1 parent ac8b224 commit 6106c2c

1 file changed

Lines changed: 23 additions & 0 deletions

File tree

archive/o/ocaml/longest-word.ml

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
(* Use custom function instead of Char.Ascii.is_white because the builtin also matches
2+
on vertical tab and form feed which are not considered whitespace for the
3+
purposes of this problem *)
4+
let is_whitespace = function ' ' | '\t' | '\n' | '\r' -> true | _ -> false
5+
6+
let longest_word_len s =
7+
let best, _ =
8+
String.fold_left
9+
(fun (best, curr) c ->
10+
if is_whitespace c then (best, 0)
11+
else
12+
let curr = curr + 1 in
13+
(Int.max best curr, curr))
14+
(0, 0) s
15+
in
16+
best
17+
18+
let () =
19+
print_endline
20+
@@
21+
match Sys.argv with
22+
| [| _; s |] when s <> "" -> string_of_int (longest_word_len s)
23+
| _ -> "Usage: please provide a string"

0 commit comments

Comments
 (0)