Messing around with SexpProcessor

July 13th, 2008
              require 'rubygems'
              require 'parse_tree'
              require 'ruby2ruby'
              
              Sexp.class_eval do
                def unbox
                  if length == 1
                    self.first
                  else
                    self
                  end
                end
              end
              
              class Lispify < SexpProcessor
                def initialize
                  super
                  self.auto_shift_type = true
                  self.require_empty   = false
                end
              
                def process_vcall(expr)
                  s(expr.first)
                end
              
                def process_call(expr)
                  expr = Sexp.from_array(expr)
              
                  first  = process(expr[0]).unbox
                  second = process(expr[2]).unbox
              
                  s(expr[1], first, second)
                end
              
                def process_array(expr)
                  process(expr.first)
                end
              end
              
              

Which results in:

              >> equation = %q{ x + x * x - x }
              >> Lispify.new.process(ParseTree.translate(equation))
              => s(:-, s(:+, :x, s(:*, :x, :x)), :x)
              >>
              

So now you’re in perfect shape to perform some kind of symbolic computation on the equation.