Advertisement
Guest User

Untitled

a guest
Aug 14th, 2018
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
OCaml 1.96 KB | None | 0 0
  1. open Js.String
  2.  
  3. module Ops = struct
  4.   type t =
  5.     | Delete of string * int
  6.     | Insert of string * string * int
  7.     | Replace of string * string * int
  8.  
  9.   let run op = match op with
  10.     | Delete (str, i) ->
  11.       (slice ~from:0 ~to_:i str) ^ (sliceToEnd ~from:(i + 1) str)
  12.     | Insert (str, char, i) ->
  13.       if i = 0 then char ^ str
  14.       else if i = length str - 1 then str ^ char
  15.       else (slice ~from:0 ~to_:i str) ^ char ^ (sliceToEnd ~from:i str)
  16.     | Replace (str, char, i) ->
  17.       (slice ~from:0 ~to_:i str) ^ char ^ (sliceToEnd ~from:(i + 1) str)
  18. end
  19.  
  20. let max_safe_int = [%raw "Number.MAX_SAFE_INTEGER"]
  21.  
  22. let mem f = fun w1 w2 p1 ->
  23.   let dict = Js.Dict.empty () in
  24.   match Js.Dict.get dict w1 with
  25.   | None ->
  26.     let result = f w1 w2 p1 in
  27.     Js.Dict.set dict w1 result;
  28.     result
  29.   | Some num -> num
  30.  
  31. let rec edit_distance w1 w2 idx =
  32.   let len1, len2 = length w1, length w2 in
  33.   if w1 = w2
  34.     then 0
  35.   else
  36.     let (c1, c2) = (get w1 idx, get w2 idx) in
  37.     if c1 = c2 then edit_distance w1 w2 (idx + 1)
  38.     else
  39.       let open Ops in
  40.       if len1 > len2 then
  41.         let delete =
  42.           edit_distance (run (Delete (w1, idx))) w2 (idx - 1)
  43.         in
  44.         1 + if idx >= len2
  45.           then delete
  46.         else
  47.           Js.Math.min_int (edit_distance (run (Replace (w1, c2, idx))) w2 (idx + 1)) delete
  48.       else if len1 < len2 then
  49.         let insert =
  50.           edit_distance (run (Insert (w1, c2, idx))) w2 (idx + 1)
  51.         in
  52.         1 + if idx >= len2
  53.           then insert
  54.         else
  55.           Js.Math.min_int (edit_distance (run (Replace (w1, c2, idx))) w2 (idx + 1)) insert
  56.       else
  57.         1 + Js.Math.min_int
  58.           (edit_distance (run (Insert (w1, c2, idx))) w2 (idx + 1))
  59.           (Js.Math.min_int
  60.             (edit_distance (run (Replace (w1, c2, idx))) w2 (idx + 1))
  61.             (edit_distance (run (Delete (w1, idx))) w2 (idx - 1)))
  62.      
  63. let minDistance w1 w2 = (mem edit_distance) w1 w2 0
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement