Class: ComaLisp

Inherits:
Object
  • Object
show all
Defined in:
lib/comalisp.rb

Instance Method Summary collapse

Constructor Details

#initialize(opts = {}) ⇒ ComaLisp

Returns a new instance of ComaLisp.



2
3
4
5
6
# File 'lib/comalisp.rb', line 2

def initialize(opts={})
  # parent is used for scoping
  @parent = opts[:parent]
  @env = opts[:env] || {}
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *args, &block) ⇒ Object (private)



87
88
89
90
91
92
93
# File 'lib/comalisp.rb', line 87

def method_missing(name,*args,&block)
  if args.empty?
    variable_lookup(name)
  else
    method_call(name,*args,&block)
  end
end

Instance Method Details

#apply(fn, args) ⇒ Object



49
50
51
# File 'lib/comalisp.rb', line 49

def apply(fn,args)
  self.send(fn,*args)
end

#call(fn, *args) ⇒ Object



45
46
47
# File 'lib/comalisp.rb', line 45

def call(fn,*args)
  self.apply(fn,args)
end

#car(lst) ⇒ Object



23
24
25
26
# File 'lib/comalisp.rb', line 23

def car(lst)
  return null if lst.size < 1
  lst[0]
end

#cdr(lst) ⇒ Object



36
37
38
39
# File 'lib/comalisp.rb', line 36

def cdr(lst)
  return [] if lst.size == 0
  lst[1..-1]
end

#cons(head, tail = nil) ⇒ Object

we use array to represent list and cons The implication is that all lists must be proper. That is (cons 1, 2) is invalid. [] is the empty list. Nothing else is the empty list. It is the fixpoint for cdr.



11
12
13
# File 'lib/comalisp.rb', line 11

def cons(head,tail=nil)
  [head,*tail]
end

#consp(o) ⇒ Object



15
16
17
# File 'lib/comalisp.rb', line 15

def consp(o)
  o.is_a? Array
end

#defun(argslist, &body) ⇒ Object



66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/comalisp.rb', line 66

def defun(argslist,&body)
  me = self
  name = argslist.shift
  eigenclass = class << self; self; end
  eigenclass.instance_eval do
    define_method(name) do |*vals|
      env = {}
      argslist.each_with_index do |arg,i|
        env[arg] = vals[i]
      end
      me.scope(env,&body)
    end
  end
end

#let(*vars, &body) ⇒ Object



53
54
55
56
57
58
59
# File 'lib/comalisp.rb', line 53

def let(*vars,&body)
  env = vars.inject({}) {|acc,(k,v)|
    acc[k] = v
    acc
  }
  scope(env,&body)
end

#list(*args) ⇒ Object



41
42
43
# File 'lib/comalisp.rb', line 41

def list(*args)
  args
end

#nullObject



28
29
30
# File 'lib/comalisp.rb', line 28

def null
  []
end

#nullp(list) ⇒ Object



32
33
34
# File 'lib/comalisp.rb', line 32

def nullp(list)
  list == null
end

#scope(env = {}, &body) ⇒ Object



61
62
63
64
# File 'lib/comalisp.rb', line 61

def scope(env={},&body)
  scope = ComaLisp.new(:parent => self, :env => env)
  scope.instance_eval(&body)
end

#set(var, val) ⇒ Object



81
82
83
# File 'lib/comalisp.rb', line 81

def set(var,val)
  @env[var.to_sym] = val
end

#tail(lst) ⇒ Object



19
20
21
# File 'lib/comalisp.rb', line 19

def tail(lst)
  lst.last
end