Class: Lisp

Inherits:
Object
  • Object
show all
Defined in:
lib/calculo/lisp.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(string, type) ⇒ Lisp

Returns a new instance of Lisp.



8
9
10
11
12
13
# File 'lib/calculo/lisp.rb', line 8

def initialize(string, type)
        @string = string
        @type = type
        @array = parse(@string)
        @result = eval_lisp(@array)
end

Instance Attribute Details

#arrayObject

Returns the value of attribute array.



5
6
7
# File 'lib/calculo/lisp.rb', line 5

def array
  @array
end

#resultObject

Returns the value of attribute result.



6
7
8
# File 'lib/calculo/lisp.rb', line 6

def result
  @result
end

#stringObject

Returns the value of attribute string.



3
4
5
# File 'lib/calculo/lisp.rb', line 3

def string
  @string
end

#typeObject

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