Build sequence diffs with List.myers_difference/2

almirsarajcic

almirsarajcic

5 hours ago

0 comments

Use List.myers_difference/2 to turn two sequences into an edit script without adding a diff dependency.

before = ["authorize", "capture", "receipt"]
after_steps = ["authorize", "fraud_check", "capture"]

List.myers_difference(before, after_steps)

# => [
#      eq: ["authorize"],
#      ins: ["fraud_check"],
#      eq: ["capture"],
#      del: ["receipt"]
#    ]

The result describes how to move from the first list toward the second. :eq elements stay, :del elements are removed, and :ins elements are inserted. Adjacent operations of the same kind are grouped into lists.

The input can be any lists, not only strings. To diff text by line, split each version into lines first. The edit script can then drive a CLI report, an audit view, or change highlighting without parsing a formatted diff.

When elements contain values that need their own nested comparison, List.myers_difference/3 accepts a callback. For strings, passing &String.myers_difference/2 produces nested :diff entries instead of treating every changed string as an indivisible replacement.

List.myers_difference/2 docs

Comments (0)

Sign in with GitHub to join the discussion