# 2012/01/28 jun hirabayashi jun@hirax.net #=========================================== class String def m2rType v v.gsub!(/^\s+/,'').gsub!(/\s+$/,'') if /^[0-9]*$/=~v v.to_i elsif /^[0-9\.]*$/=~v v.to_f else v end end def to_rb return self unless /[{}]+/=~self obj = m2r( self ) l = obj.length-1 l.times do |i| (l-i).times do |j| index = obj[i+j+1].index( 'hoge'+(i+1).to_s ) obj[i+j+1][index] = obj[i] if index end end obj[l] end def m2r str @mathArray = Array.new unless @mathArray if /(\{[^\{\}]*?\})/=~str s = $1 val = s.gsub( /[\{\}]+/, '' ).split(',').map do |v| m2rType v end @mathArray << val m2r( str.sub( s, 'hoge'+@mathArray.length.to_s ) ) else @mathArray end end end #=========================================== class Array def to_math obj isFirst = true str = '{' obj.each do |item| if item.instance_of?(Array) if isFirst str = str + to_ma( item ) isFirst = false else str = str + ',' + to_math( item ) end else if isFirst str = str + item.to_s isFirst = false else str = str + ',' + item.to_s end end end str + '}' end def to_ma to_math self end end #=========================================== class Mathematica require 'Wolfram.NETLink' include Wolfram::NETLink PAR="-linkmode launch -linkname 'C:\\Program Files (x86)\\Wolfram Research\\...\\MathKernel.exe'" def Mathematica.callback proc { @kernelLink.EvaluateToInputForm 'MVClose[]', 0 } end def initialize() @kernelLink = MathLinkFactory.CreateKernelLink PAR @kernelLink.WaitAndDiscardAnswer end def do( q ) @kernelLink.EvaluateToInputForm q, 0 end end module MathematicaModule def method_missing( functionName, *args) $mathematica = Mathematica.new unless $mathematica if self.kind_of? Array obj = self.to_ma else obj = self end result = $mathematica.do [functionName,'[',([obj]+args).join(','),']'].join result.to_rb end end #=========================================== class Object include MathematicaModule end if __FILE__ == $PROGRAM_NAME require 'pp' pp 'x^2 == 3'.Solve 'x' pp '2 x + 3 == 0'.Solve 'x' pp ['x + 2 y == 1','3 x - y == 0'].Solve '{x,y}' pp [1,2,3].Sin.N end