Class: Lisp
- Inherits:
-
Object
- Object
- Lisp
- Defined in:
- lib/calculo/lisp.rb
Instance Attribute Summary collapse
-
#array ⇒ Object
Returns the value of attribute array.
-
#result ⇒ Object
Returns the value of attribute result.
-
#string ⇒ Object
Returns the value of attribute string.
-
#type ⇒ Object
Returns the value of attribute type.
Instance Method Summary collapse
- #eval_lisp(array) ⇒ Object
- #execute(array, type) ⇒ Object
-
#initialize(string, type) ⇒ Lisp
constructor
A new instance of Lisp.
- #innermost_pair(array) ⇒ Object
Constructor Details
Instance Attribute Details
#array ⇒ Object
Returns the value of attribute array.
5 6 7 |
# File 'lib/calculo/lisp.rb', line 5 def array @array end |
#result ⇒ Object
Returns the value of attribute result.
6 7 8 |
# File 'lib/calculo/lisp.rb', line 6 def result @result end |
#string ⇒ Object
Returns the value of attribute string.
3 4 5 |
# File 'lib/calculo/lisp.rb', line 3 def string @string end |
#type ⇒ Object
Returns the value of attribute type.
4 5 6 |
# File 'lib/calculo/lisp.rb', line 4 def type @type end |
Instance Method Details
#eval_lisp(array) ⇒ Object
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
# File 'lib/calculo/lisp.rb', line 43 def eval_lisp(array) length, l, r = innermost_pair(array) result = execute(array[l..r],type) if length > 2 # Inserts the result in between the portions # of the array not including the portion just # used to calculate the result new_array = array[0..(l-1)] + [result] + array[(r+1)..-1] eval_lisp(new_array) elsif length == 2 return result end end |
#execute(array, type) ⇒ Object
16 17 18 19 20 21 22 23 |
# File 'lib/calculo/lisp.rb', line 16 def execute(array,type) case type when 'lisp' array[2..-2].reduce(array[1].to_sym) when 'reverse-lisp' || 'reverse' array[1..-3].reverse.reduce(array[-2].to_sym) end end |
#innermost_pair(array) ⇒ Object
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
# File 'lib/calculo/lisp.rb', line 25 def innermost_pair(array) l_parens = [] r_parens = [] array.each_with_index do |item, index| if item == "(" l_parens.push(index) elsif item == ")" r_parens.push(index) end end total_length = l_parens.length + r_parens.length return [total_length, l_parens[-1], r_parens[0]] end |