Chervil is a toy Lisp interpreter written in Ruby
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

function.rb 831B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. module Chervil::AST
  2. class Function
  3. attr_reader :name
  4. attr_reader :params
  5. attr_reader :body
  6. def initialize(name, params, body)
  7. @name = name
  8. @params = params
  9. @body = body
  10. end
  11. def ==(other)
  12. @name == other.name && @params == other.params && @body == other.body
  13. end
  14. def evaluate(env)
  15. self
  16. end
  17. def call(args, env)
  18. unless @params.size == args.size
  19. raise "Expected #{params.size} arguments but received #{args.size}"
  20. end
  21. @params.zip(args).each do |key, value|
  22. env.set(key.name, value)
  23. end
  24. current_expr = nil
  25. @body.each do |expr|
  26. current_expr = expr.evaluate(env)
  27. end
  28. current_expr
  29. end
  30. def to_s
  31. "<function: #{@name.name}(#{@params.map(&:name).join(' ')})>"
  32. end
  33. end
  34. end