Wednesday, May 2, 2007

Transmoglyphing textual logic expression into Latex math

Recently I've been doing some exercises which included a lot of logic expressions. Writing those in Latex becomes really tedious after a while, so I got sidetracked and wrote a small ruby program :-) It transforms a textual logic expression to the Latex equivalent.

For instance, this is a textual of a common logic function (can you see which one?):
(x and not y) or (!x && y)

It translates into latex math:
$(x \wedge \neg y) \vee ( \neg x \wedge y)$

When rendered it looks like this:


Other things like implication, biiimplication and entailment are also supported. The syntax allows a certain degree of freedom in choice of textual logic operators.

The code:


#!/usr/bin/env ruby
# Encode text with logic expressions as a latex math expression

symbols = {
'\wedge' => [ 'and', '&&' ],
'\vee' => [ 'or', '||' ],
'\neg' => [ '^', '!', 'not' ],
'\Leftrightarrow' => [ '<=>', '<->' ],
'\Rightarrow' => [ '=>', '->' ],
'\models' => [ ':-', ':=', 'entails' ]
}

match_exp = {}
symbols.keys.each { |k| symbols[k].each { |re| match_exp[re] = k } }

# Sort string by their length so that longest regexps are matched first

class String
def <=>(other)
other.length <=> length
end
end

loop do
puts "Enter logic text:"
text = $stdin.gets.chomp
break if text == "quit"

match_exp.keys.reverse.each { |k| text.gsub!(k, " #{match_exp[k]} ") }
puts "Latex math expr: $#{text.chomp}$"
end

No comments: