Sha256: e558c46729885768cac451532796c4b869f97858dee4c2b9d6d074fdf0b2463d

Contents?: true

Size: 1.37 KB

Versions: 3

Compression:

Stored size: 1.37 KB

Contents

# import all functions from Ruby's Math module
require_relative '../function'

module Dentaku
  module AST
    class RubyMath < Function
      def self.[](method)
        klass_name = method.to_s.capitalize
        klass = const_set(klass_name , Class.new(self))
        klass.implement(method)
        const_get(klass_name)
      end

      def self.implement(method)
        @name = method
        @implementation = Math.method(method)
      end

      def self.name
        @name
      end

      def self.arity
        @implementation.arity < 0 ? nil : @implementation.arity
      end

      def self.min_param_count
        @implementation.parameters.select { |type, _name| type == :req }.count
      end

      def self.max_param_count
        @implementation.parameters.select { |type, _name| type == :rest }.any? ? Float::INFINITY : @implementation.parameters.count
      end

      def self.call(*args)
        @implementation.call(*args)
      end

      def value(context = {})
        args = @args.flatten.map { |a| Dentaku::AST::Function.numeric(a.value(context)) }
        self.class.call(*args)
      end

      ARRAY_RETURN_TYPES = [:frexp, :lgamma].freeze

      def type
        ARRAY_RETURN_TYPES.include?(@name) ? :array : :numeric
      end
    end
  end
end

Math.methods(false).each do |method|
  Dentaku::AST::Function.register_class(method, Dentaku::AST::RubyMath[method])
end

Version data entries

3 entries across 3 versions & 2 rubygems

Version Path
dentaku_zevo-3.5.2 lib/dentaku/ast/functions/ruby_math.rb
dentaku-3.5.1 lib/dentaku/ast/functions/ruby_math.rb
dentaku-3.5.0 lib/dentaku/ast/functions/ruby_math.rb