Class: Keisan::Functions::If

Inherits:
Keisan::Function show all
Defined in:
lib/keisan/functions/if.rb

Instance Attribute Summary

Attributes inherited from Keisan::Function

#arity, #name

Instance Method Summary collapse

Methods inherited from Keisan::Function

#unbound_variables

Constructor Details

#initializeIf

Returns a new instance of If.



4
5
6
# File 'lib/keisan/functions/if.rb', line 4

def initialize
  super("if", ::Range.new(2,3))
end

Instance Method Details

#differentiate(ast_function, variable, context = nil) ⇒ Object



48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/keisan/functions/if.rb', line 48

def differentiate(ast_function, variable, context = nil)
  validate_arguments!(ast_function.children.count)
  context ||= Context.new
  AST::Function.new(
    [
      ast_function.children[0],
      ast_function.children[1].differentiate(variable, context),
      ast_function.children[2].differentiate(variable, context)
    ],
    @name
  )
end

#evaluate(ast_function, context = nil) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/keisan/functions/if.rb', line 13

def evaluate(ast_function, context = nil)
  validate_arguments!(ast_function.children.count)
  context ||= Context.new
  bool = ast_function.children[0].evaluate(context).to_node

  if bool.is_a?(AST::Boolean)
    node = bool.value ? ast_function.children[1] : ast_function.children[2]
    node.to_node.evaluate(context)
  elsif bool.is_constant?
    raise Keisan::Exceptions::InvalidFunctionError.new("if statement must work on booleans, other constants are not supported")
  else
    ast_function
  end
end

#simplify(ast_function, context = nil) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/keisan/functions/if.rb', line 28

def simplify(ast_function, context = nil)
  validate_arguments!(ast_function.children.count)
  context ||= Context.new
  bool = ast_function.children[0].simplify(context).to_node

  if bool.is_a?(AST::Boolean)
    if bool.value
      ast_function.children[1].to_node.simplify(context)
    elsif ast_function.children.size >= 2
      ast_function.children[2].to_node.simplify(context)
    else
      Keisan::AST::Null.new
    end
  elsif bool.is_constant?
    raise Keisan::Exceptions::InvalidFunctionError.new("if statement must work on booleans, other constants are not supported")
  else
    ast_function
  end
end

#value(ast_function, context = nil) ⇒ Object



8
9
10
11
# File 'lib/keisan/functions/if.rb', line 8

def value(ast_function, context = nil)
  validate_arguments!(ast_function.children.count)
  evaluate(ast_function, context)
end