Sha256: 596ad70b65d3595e49c14303af9a6db362f4216de13ff39a67342b9b10216a5b

Contents?: true

Size: 1.11 KB

Versions: 3

Compression:

Stored size: 1.11 KB

Contents

module Basic101

  class UserDefinedFunction < Function

    include Identity

    def initialize(identifier, parameters, expression)
      @identifier = identifier
      @parameters = parameters
      @expression = expression
    end

    def name
      @identifier.to_s
    end

    def call(runtime, args)
      raise InvalidArgumentError unless args.size == @parameters.size
      save_parameters(runtime)
      bind_arguments(runtime, args)
      result = @expression.eval(runtime)
      restore_parameters(runtime)
      result
    end

    protected

    def state
      [@identifier, @parameters, @expression]
    end

    private

    def save_parameters(runtime)
      @original_parameter_values = @parameters.map do |parameter|
        parameter.eval(runtime)
      end
    end

    def bind_arguments(runtime, args)
      @parameters.zip(args).each do |parameter, arg|
        parameter.assign(runtime, arg.eval(runtime))
      end
    end

    def restore_parameters(runtime)
      @parameters.zip(@original_parameter_values) do |parameter, value|
        parameter.assign(runtime, value)
      end
    end

  end

end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
basic101-0.4.0 lib/basic101/user_defined_function.rb
basic101-0.2.0 lib/basic101/user_defined_function.rb
basic101-0.1.0 lib/basic101/user_defined_function.rb