// In this pset, we're proving a classic algorithm for computing *edit // distances* between strings. See this intro to the topic: // https://en.wikipedia.org/wiki/Edit_distance module Defs { // We think about transforming one string into another by repeatedly applying // edits from this menu. datatype Edit = | Add(character: char) | Delete | Replace(character: char) | Skip datatype Option = None | Some(value: T) // This function explains what it means to transform a string with a sequence // of edits. Not all edit sequences are well-formed for a given input string, // and the function returns None when there is a mismatch. ghost function ApplyEdits(es: seq, s: string): Option { if |es| == 0 then // No more edits? We're done exactly when the input string is empty. // Otherwise, some more steps are expected to consume all characters. if |s| == 0 then Some("") else None else match es[0] case Add(ch) => ( match ApplyEdits(es[1..], s) case None => None case Some(s') => Some([ch] + s') ) case Delete => ( if |s| == 0 then None else ApplyEdits(es[1..], s[1..]) ) case Replace(ch) => ( if |s| == 0 then None else match ApplyEdits(es[1..], s[1..]) case None => None case Some(s') => Some([ch] + s') ) case Skip => ( // Note that Skip preserves the value of the first character of the // input string, while Replace may change it. Why not always just use // Replace? See the next definition.... if |s| == 0 then None else match ApplyEdits(es[1..], s[1..]) case None => None case Some(s') => Some([s[0]] + s') ) } // We explain how many actual changes an edit sequence requires, where a Skip // is considered *not* to make a change. ghost function Cost(es: seq): nat { if |es| == 0 then 0 else if es[0] == Skip then Cost(es[1..]) else 1 + Cost(es[1..]) } // Now we can define when two strings have a claimed edit distance d. ghost predicate IsEditDistance(s1: string, s2: string, d: nat) { // First, there exists an applicable edit sequence of the claimed length. (exists es :: ApplyEdits(es, s1) == Some(s2) && Cost(es) == d) // Second, any applicable edit sequence has length at least that high. // In other words, d is a true minimum length. && (forall es :: ApplyEdits(es, s1) == Some(s2) ==> Cost(es) >= d) } function Min(n: nat, m: nat): nat { if n < m then n else m } }