File: spellcheck.ml

package info (click to toggle)
ppxlib 0.15.0-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, sid
  • size: 1,284 kB
  • sloc: ml: 17,184; sh: 149; makefile: 36; python: 36
file content (32 lines) | stat: -rw-r--r-- 958 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
open! Import

let spellcheck names name =
  let cutoff =
    match String.length name with
    | 1 | 2 -> 0
    | 3 | 4 -> 1
    | 5 | 6 -> 2
    | _ -> 3
  in
  let _, suggestions =
    List.fold_left names ~init:(Int.max_int, [])
      ~f:(fun ((best_distance, names_at_best_distance) as acc) registered_name ->
        match Ocaml_common.Misc.edit_distance name registered_name cutoff with
        | None -> acc
        | Some dist ->
          if dist < best_distance then
            (dist, [registered_name])
          else if dist > best_distance then
            acc
          else
            (dist, registered_name :: names_at_best_distance))
  in
  match List.rev suggestions |> List.filter ~f:(String.(<>) name) with
  | [] -> None
  | last :: rev_rest ->
    Some
      (Printf.sprintf "Hint: Did you mean %s%s%s?"
         (String.concat ~sep:", " (List.rev rev_rest))
         (if List.is_empty rev_rest then "" else " or ")
         last)
;;