Class: Keisan::Functions::ProcFunction

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

Direct Known Subclasses

Rand, Sample

Instance Attribute Summary

Attributes inherited from Keisan::Function

#name

Instance Method Summary collapse

Constructor Details

#initialize(name, function_proc) ⇒ ProcFunction

Returns a new instance of ProcFunction.



4
5
6
7
8
9
# File 'lib/keisan/functions/proc_function.rb', line 4

def initialize(name, function_proc)
  raise Keisan::Exceptions::InvalidFunctionError.new unless function_proc.is_a?(Proc)

  super(name)
  @function_proc = function_proc
end

Instance Method Details

#call(context, *args) ⇒ Object



11
12
13
# File 'lib/keisan/functions/proc_function.rb', line 11

def call(context, *args)
  @function_proc.call(*args)
end

#evaluate(ast_function, context = nil) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/keisan/functions/proc_function.rb', line 21

def evaluate(ast_function, context = nil)
  context ||= Keisan::Context.new

  ast_function.instance_variable_set(
    :@children,
    ast_function.children.map {|child| child.evaluate(context)}
  )

  if ast_function.children.all? {|child| child.well_defined?(context)}
    value(ast_function, context).to_node.evaluate(context)
  else
    ast_function
  end
end

#simplify(ast_function, context = nil) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/keisan/functions/proc_function.rb', line 36

def simplify(ast_function, context = nil)
  context ||= Context.new

  ast_function.instance_variable_set(
    :@children,
    ast_function.children.map {|child| child.evaluate(context)}
  )

  if ast_function.children.all? {|child| child.is_a?(Keisan::AST::ConstantLiteral)}
    value(ast_function, context).to_node.simplify(context)
  else
    ast_function
  end
end

#value(ast_function, context = nil) ⇒ Object



15
16
17
18
19
# File 'lib/keisan/functions/proc_function.rb', line 15

def value(ast_function, context = nil)
  context ||= Keisan::Context.new
  argument_values = ast_function.children.map {|child| child.value(context)}
  call(context, *argument_values)
end