on 14ceff4 help sign in
138 lines 2.7 kB history raw
1---
2title: Ruby
3sort: 2
4next: true
5---
7# Ruby
9From [T.J. Corcoran](https://github.com/TJamesCorcoran/nock/blob/master/nock.rb):
11```
12def str_to_tree(str)
13 arr = []
14 str.scan(/\+|\=|\?|\/|\*|\[|\]|\d+/).each do |token|
15 end
16end
18def max_depth(arr)
19 ret = arr.is_a?(Array) ? [max_depth(arr[0]), max_depth(arr[1])].max + 1 : 1
20 ret
21end
23def pp(arr)
24 depth = max_depth(arr)
25 space = 128
26 1.up_to(8) do |depth|
27 space = space / 2
28 min = 2 ** (depth - 1)
29 max = (2 ** depth) - 1
30 min.upto(max) { |axis|
31 end
33end
35def norm(arr)
36 return arr unless arr.is_a?(Array)
37 while arr.size > 2
38 size = arr.size
39 arr[size - 2] = [ arr[size - 2], arr.pop ]
40 end
41 arr = arr.map { |x| norm(x) }
42end
44def wut(arr)
45 arr.is_a?(Array) ? YES : NO
46end
48def lus(atom)
49 raise "not an atom" unless atom.is_a?(Fixnum)
50 atom + 1
51end
53def tis(arr)
54 raise "not pair" unless arr.is_a?(Array) && arr.size == 2
55 ( arr[0] == arr[1] ) ? YES : NO
56end
58def slot(axis, arr, allow_error = true)
59 raise "axis on atom" unless arr.is_a?(Array)
60 return arr if axis == 1
61 return arr[0] if axis == 2
62 return arr[1] if axis == 3
63 return slot(2, slot(axis/2, arr)) if (axis %2) == 0
64 return slot(3, slot(axis/2, arr))
65end
68def nock(arr)
69 raise "error: nocking an atom" unless arr.is_a?(Array)
71 oper = slot(4, arr)
72 a = slot(2, arr)
73 b = slot(5, arr)
75 if oper.is_a?(Array)
76 return [ nock( [ a, [b, c]]), nock( [a, d]) ]
77 end
80 case oper
81 when 0 then
82 slot(b,a )
84 when 1 then
85 b
87 when 2 then
88 b_prime = slot(2, b)
89 c = slot(3,b)
90 nock( [ nock([a, b_primce]), nock([a, c]) ])
92 when 3 then
93 wut(nock([a, b]))
95 when 4 then
96 lus(nock([a, b]))
98 when 5 then
99 tis(nock([a, b]))
101 when 6 then
102 b_prime = slot(2, b)
103 c = slot(6,b)
104 d = slot(7,b)
105 nock( norm([a, 2, [0, 1], 2, [1, c, d], [1, 0], 2, [1, 2, 3], [1, 0], 4, 4, b]) )
107 when 7 then
108 b_prime = slot(2, b)
109 c = slot(3,b)
110 nock( norm ([a, 2, b_prime, 1, c]))
112 when 8 then
113 b_prime = slot(2, b)
114 c = slot(3,b)
115 nock( norm ([a, 7, [[7, [0, 1], b_prime], 0, 1], c]))
117 when 9 then
118 b_prime = slot(2, b)
119 c = slot(3,b)
120 nock( norm ([a, 7, c, 2, [0, 1], 0, b_prime]))
122 when 10 then
123 if wut(slot(2,b)) == TRUE
124 b_prime = slot(4, b)
125 c = slot(5, b)
126 d = slot(3, b)
127 c = slot(3,b)
128 nock( norm ([a, 8, c, 7, [0, 3], d]))
129 else
130 b_prime = slot(2, b)
131 c = slot(3, b)
132 nock( norm ([a, 10, [b, c]]))
133 end
134 else
135 raise "error: unknown opcode #{oper.inspect}"
136 end
137end
138```