on 5a942e0 help sign in
139 lines 2.7 kB history raw
1:- :~ navhome/'/docs/'
2 next/'true'
3 sort/'2'
4 title/'Ruby'
5 ==
6;>
8# Ruby
10From [T.J. Corcoran](https://github.com/TJamesCorcoran/nock/blob/master/nock.rb):
12```
13def str_to_tree(str)
14 arr = []
15 str.scan(/\+|\=|\?|\/|\*|\[|\]|\d+/).each do |token|
16 end
17end
19def max_depth(arr)
20 ret = arr.is_a?(Array) ? [max_depth(arr[0]), max_depth(arr[1])].max + 1 : 1
21 ret
22end
24def pp(arr)
25 depth = max_depth(arr)
26 space = 128
27 1.up_to(8) do |depth|
28 space = space / 2
29 min = 2 ** (depth - 1)
30 max = (2 ** depth) - 1
31 min.upto(max) { |axis|
32 end
34end
36def norm(arr)
37 return arr unless arr.is_a?(Array)
38 while arr.size > 2
39 size = arr.size
40 arr[size - 2] = [ arr[size - 2], arr.pop ]
41 end
42 arr = arr.map { |x| norm(x) }
43end
45def wut(arr)
46 arr.is_a?(Array) ? YES : NO
47end
49def lus(atom)
50 raise "not an atom" unless atom.is_a?(Fixnum)
51 atom + 1
52end
54def tis(arr)
55 raise "not pair" unless arr.is_a?(Array) && arr.size == 2
56 ( arr[0] == arr[1] ) ? YES : NO
57end
59def slot(axis, arr, allow_error = true)
60 raise "axis on atom" unless arr.is_a?(Array)
61 return arr if axis == 1
62 return arr[0] if axis == 2
63 return arr[1] if axis == 3
64 return slot(2, slot(axis/2, arr)) if (axis %2) == 0
65 return slot(3, slot(axis/2, arr))
66end
69def nock(arr)
70 raise "error: nocking an atom" unless arr.is_a?(Array)
72 oper = slot(4, arr)
73 a = slot(2, arr)
74 b = slot(5, arr)
76 if oper.is_a?(Array)
77 return [ nock( [ a, [b, c]]), nock( [a, d]) ]
78 end
81 case oper
82 when 0 then
83 slot(b,a )
85 when 1 then
86 b
88 when 2 then
89 b_prime = slot(2, b)
90 c = slot(3,b)
91 nock( [ nock([a, b_primce]), nock([a, c]) ])
93 when 3 then
94 wut(nock([a, b]))
96 when 4 then
97 lus(nock([a, b]))
99 when 5 then
100 tis(nock([a, b]))
102 when 6 then
103 b_prime = slot(2, b)
104 c = slot(6,b)
105 d = slot(7,b)
106 nock( norm([a, 2, [0, 1], 2, [1, c, d], [1, 0], 2, [1, 2, 3], [1, 0], 4, 4, b]) )
108 when 7 then
109 b_prime = slot(2, b)
110 c = slot(3,b)
111 nock( norm ([a, 2, b_prime, 1, c]))
113 when 8 then
114 b_prime = slot(2, b)
115 c = slot(3,b)
116 nock( norm ([a, 7, [[7, [0, 1], b_prime], 0, 1], c]))
118 when 9 then
119 b_prime = slot(2, b)
120 c = slot(3,b)
121 nock( norm ([a, 7, c, 2, [0, 1], 0, b_prime]))
123 when 10 then
124 if wut(slot(2,b)) == TRUE
125 b_prime = slot(4, b)
126 c = slot(5, b)
127 d = slot(3, b)
128 c = slot(3,b)
129 nock( norm ([a, 8, c, 7, [0, 3], d]))
130 else
131 b_prime = slot(2, b)
132 c = slot(3, b)
133 nock( norm ([a, 10, [b, c]]))
134 end
135 else
136 raise "error: unknown opcode #{oper.inspect}"
137 end
138end
139```