Class: Keisan::Functions::ProcFunction

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

Direct Known Subclasses

MathFunction, Rand, Sample

Instance Attribute Summary collapse

Attributes inherited from Keisan::Function

#arity, #name

Instance Method Summary collapse

Methods inherited from Keisan::Function

#differentiate, #unbound_variables

Constructor Details

#initialize(name, function_proc) ⇒ ProcFunction

Returns a new instance of ProcFunction.



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

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

  super(name, function_proc.arity)
  @function_proc = function_proc
end

Instance Attribute Details

#function_procObject (readonly)

Returns the value of attribute function_proc.



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

def function_proc
  @function_proc
end

Instance Method Details

#call(context, *args) ⇒ Object



13
14
15
16
# File 'lib/keisan/functions/proc_function.rb', line 13

def call(context, *args)
  validate_arguments!(args.count)
  function_proc.call(*args).to_node
end

#evaluate(ast_function, context = nil) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/keisan/functions/proc_function.rb', line 25

def evaluate(ast_function, context = nil)
  validate_arguments!(ast_function.children.count)
  context ||= Context.new

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

  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



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/keisan/functions/proc_function.rb', line 41

def simplify(ast_function, context = nil)
  validate_arguments!(ast_function.children.count)
  context ||= Context.new

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

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

#value(ast_function, context = nil) ⇒ Object



18
19
20
21
22
23
# File 'lib/keisan/functions/proc_function.rb', line 18

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