Last active
January 30, 2025 13:44
-
-
Save fujidig/c140fd655c6362c52326a3760a83e669 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function DualizeError() {} | |
DualizeError.prototype = new Error(); | |
function parseInequality(str) { | |
var m = str.match(/^(.+?)(\s*(?:\\leq?|=)\s*)(.+)$/); | |
if (m) { | |
return [m[1], m[2], m[3]]; | |
} else { | |
throw new DualizeError("cannot parse it"); | |
} | |
} | |
function dualizeInvariant(str) { | |
var m; | |
if (m = str.match(/^(\s+)(.+)$/)) { | |
return m[1] + dualizeInvariant(m[2]); | |
} | |
if (m = str.match(/^\\cov\((.+)\)$/)) { | |
return "\\non("+m[1]+")"; | |
} | |
if (m = str.match(/^\\non\((.+)\)$/)) { | |
return "\\cov("+m[1]+")"; | |
} | |
if (m = str.match(/^\\add\((.+)\)$/)) { | |
return "\\cof("+m[1]+")"; | |
} | |
if (m = str.match(/^\\cof\((.+)\)$/)) { | |
return "\\add("+m[1]+")"; | |
} | |
if (m = str.match(/^\\frakb$/)) { | |
return "\\frakd"; | |
} | |
if (m = str.match(/^\\frakd$/)) { | |
return "\\frakb"; | |
} | |
if (m = str.match(/^\\min(\s*)\\{(.+)\\}$/)) { | |
return "\\max"+m[1]+"\\{"+m[2].split(",").map((x) => dualizeInvariant(x)).join(",")+"\\}"; | |
} | |
if (m = str.match(/^\\max(\s*)\\{(.+)\\}$/)) { | |
return "\\min"+m[1]+"\\{"+m[2].split(",").map((x) => dualizeInvariant(x)).join(",")+"\\}"; | |
} | |
throw new DualizeError("cannot dualize it"); | |
} | |
function dualizeInequality(str) { | |
var parsed = parseInequality(str); | |
var lhs = parsed[0]; | |
var op = parsed[1]; | |
var rhs = parsed[2]; | |
if (op.match(/^\s*=\s*$/)) { | |
return dualizeInvariant(lhs) + op + dualizeInvariant(rhs); | |
} else { | |
return dualizeInvariant(rhs) + op + dualizeInvariant(lhs); | |
} | |
} | |
var line = editor.text(cursor.lineNumber()); | |
var re = /\$([^$]+)\$([^$]*)$/g; | |
var matched = re.exec(line); | |
if (matched) { | |
var to = re.lastIndex; | |
var from = to - matched[0].length; | |
var result; | |
try { | |
var result = dualizeInequality(matched[1]); | |
} catch(e) { | |
alert(e); | |
var result = null; | |
} | |
if (result) { | |
cursor.beginEditBlock(); | |
cursor.eraseLine(); | |
cursor.insertText(line.slice(0, from)); | |
cursor.insertText("$"+matched[1]+"$"); | |
cursor.insertText(" and $"+result+"$"+matched[2]); | |
cursor.insertText(line.slice(to, -1)); | |
cursor.insertLine(); | |
cursor.endEditBlock(); | |
cursor.movePosition(1, cursorEnums.Left); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment