Module: MLL

Defined in:
lib/mll.rb

Class Method Summary collapse

Class Method Details

.define_listable_function(name, &block) ⇒ Object



206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
# File 'lib/mll.rb', line 206

def define_listable_function name, &block
  (class << self; self end).class_eval do
    define_method name do
      lambda do |*args|
        case args.map{ |i| i.respond_to? :map }
          when [true] ; args.first.lazy.map &method(name).call
          when [true, true] ; args.first.lazy.zip(args.last).map{ |i, j| send(name)[i, j] }
          when [true, false] ; args.first.lazy.map{ |i| send(name)[i, args.last] }
          when [false, true] ; args.last.lazy.map{ |i| send(name)[args.first, i] }
        else
          block.call *args
        end
      end
    end
  end
end

.define_orderless_function(name, start, &block) ⇒ Object



258
259
260
261
262
263
264
265
266
267
268
# File 'lib/mll.rb', line 258

def self.define_orderless_function name, start, &block
  (class << self; self end).class_eval do # http://stackoverflow.com/a/12792313/322020
    define_method name do
     lambda do |*args|
        args.inject(start) do |memo, obj|
          block.call memo, obj
        end
      end
    end
  end
end

.dimensionsObject



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/mll.rb', line 5

def dimensions
  lambda do |list, limit = nil|
    list = [list]
    enumerator = Enumerator.new do |e|
      # String.size shall not pass
      while list.all?{ |i| i.respond_to? :each } &&
            list.map(&:size).uniq.size == 1
        # TODO refactor into depth-first yielding
        e << list.first.size
        list.flatten! 1
      end
    end
    limit ? enumerator.lazy.take(limit) : enumerator
  end
end

.fold_listObject



60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/mll.rb', line 60

def fold_list
  lambda do |x, list, f = nil|
    unless f
      f = list
      x, *list = x.to_a
    end
    # TODO use Ruby#inject ?
    Enumerator.new do |e|
      e << x
      list.each do |i|
        e << x = f.call(x, i)
      end
    end
  end
end

.gridObject



119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
# File 'lib/mll.rb', line 119

def grid
  lambda do |table, **options|
    # TODO negative spacings?
    options[:spacings] ||= [1, 1]
    spacings_horizontal, spacings_vertical = [*options[:spacings]]
    spacings_vertical ||= 1
    raise ArgumentError.new("unknown value of :alignment option '#{options[:alignment]}'") unless \
      alignment = {
        nil => :center,
        :center => :center,
        :left => :ljust,
        :right => :rjust,
      }[options[:alignment]]
    frames = {
      nil  => "              ",
      true => "┃ ┏┓ ┗┛━ ┃━━┃ ",
      :all => "┃┃┏┓╋┗┛━━┣┳┻┫ ",
    }[options[:frame]]
    raise ArgumentError.new("unknown value of :frame option '#{options[:frame]}'") if options[:frame] && !frames
    # TODO smth with this #.all?
    table = [table] unless table.all?{ |e| e.respond_to? :each }
    width = table.map(&:size).max - 1
    strings = table.map{ |row| row.dup.tap{ |a| a[width] = a[width] }.map(&:to_s) }
    sizes = strings.transpose.map{ |col| col.map(&:size).max + [spacings_horizontal * 2 - 2, 0].max }
    # TODO https://reference.wolfram.com/language/ref/Alignment.html
    border_vertical  = [frames[9], sizes.map{ |size|  frames[8] * size }.join((frames[4] unless spacings_horizontal.zero?)), frames[12]]
    spacing_vertical = [frames[0], sizes.map{ |size| frames[13] * size }.join((frames[0] unless spacings_horizontal.zero?)), frames[0]]
    gap_vertical = lambda do |i|
      j = i - 1
      [*-j..j].map{ |k| [border_vertical][k] || spacings_vertical }
    end.call spacings_vertical
    [
      [frames[2], sizes.map{ |size| frames[7] * size }.join((frames[10] unless spacings_horizontal.zero?)), frames[3]].join,
      *([spacing_vertical.join] * [spacings_vertical - 1, 0].max),
      strings.map{ |row| [frames[0], row.zip(sizes).map{ |str, size|
        str.method(alignment).call(size)
      }.join((frames[1] unless spacings_horizontal.zero?)), frames[0]].join }.join(
        ?\n + gap_vertical.map{ |gap| gap.join + ?\n }.join
      ),
      *([spacing_vertical.join] * [spacings_vertical - 1, 0].max),
      [frames[5], sizes.map{ |size| frames[7] * size }.join((frames[11] unless spacings_horizontal.zero?)), frames[6]].join,
    ].join(?\n) + ?\n
  end
end

.mapObject



76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
# File 'lib/mll.rb', line 76

def map
  # TODO validate depths
  # TODO break on passing all depths
  lambda do |list, depths, f = nil|
    depths, f = [1], depths unless f
    depths = Range.new(*depths) if depths.size == 2
    depths = Range.new(1,depths) if depths.is_a? Integer
    g = lambda do |list, depth|
      next list unless list.is_a? Array
      temp = list.lazy.map{ |i| g[i, depth + 1] }
      temp = temp.lazy.map &f if depths.include? depth
      temp
    end
    g[list, 1]
  end
end

.meanObject



273
274
275
276
277
# File 'lib/mll.rb', line 273

def self.mean
  lambda do |list|
    divide[times[plus[*list], 1.0], list.size]
  end
end

.nestObject



34
35
36
37
38
39
# File 'lib/mll.rb', line 34

def nest
  lambda do |expr, n, f|
    n.times{ expr = f.call expr }
    expr
  end
end

.nest_listObject



41
42
43
44
45
46
47
48
49
50
# File 'lib/mll.rb', line 41

def nest_list
  lambda do |expr, n, f|
    Enumerator.new do |e|
      e << expr
      n.times do
        e << expr = f.call(expr)
      end
    end
  end
end

.nest_whileObject



52
53
54
55
56
57
58
# File 'lib/mll.rb', line 52

def nest_while
  # TODO finish me
  lambda do |expr, f, test|
    expr = f[expr] while test[expr]
    expr
  end
end

.riffleObject



178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
# File 'lib/mll.rb', line 178

def riffle
  lambda do |*args|
    case args.size
      when 2
        next riffle[*args, [2,-2,2]] unless args[1].respond_to?(:each) && args[0].size == args[1].size
        Enumerator.new do |e|
          args[0].zip(args[1]){ |i, j| e << i << j }
        end
      when 3
        args[2] = [args[2], -2, args[2]] unless args[2].respond_to? :each
        Enumerator.new do |e|
          min = (args[2][0] < 0) ? (args[0].size + args[2][0]) : args[2][0] - 1
          max = (args[2][1] < 0) ? (args[0].size + args[2][1]) : args[2][1]
          min, max = max, min if args[2][0] < 0
          step = args[2][2]
          pos = 0
          args[0].each_with_index do |x, i|
            # TODO make it not destructive
            (pos += 1; e << x)
            (pos += 1; e << (args[1].respond_to?(:each) ? args[1].rotate!.last : args[1])) if min - 1 <= i && i <= max && (pos - min) % step == 0
          end
        end
    else
      raise ArgumentError.new("wrong number of arguments (#{args.size} for 2..3)")
    end
  end
end

.subdivideObject



164
165
166
167
168
169
170
171
172
173
174
175
176
# File 'lib/mll.rb', line 164

def subdivide
  lambda do |*args|
    case args.size
      when 1 ; subdivide[1, args[0]]
      when 2 ; subdivide[0, args[0], args[1]]
      when 3
        # raise ArgumentError.new("can't divide into 0 parts") if args[2].zero?
        range[args[0], args[1], (args[1] - args[0]) * 1.0 / args[2]]
    else
      raise ArgumentError.new("wrong number of arguments (#{args.size} for 1..3)")
    end
  end
end

.tableObject



93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
# File 'lib/mll.rb', line 93

def table
  lambda do |f, *args|
    [].tap do |result|
      [[result, args.map{ |r| # add lazy?
        r.respond_to?(:map) && r.first.respond_to?(:map) ?
          r.first : range[*r]
      }]].tap do |stack|
        stack.each do |ai, ri|
          # TODO try to make #table lazy (Enumerator instead of Array)
          # "no implicit conversion of Enumerator::Lazy into Array"
          # "undefined method `replace' for #<Enumerator::Lazy: []>"
          ai.replace ri.first.map{ |i|
            if ri.size == 1
              f.respond_to?(:call) ? f.call(*ai, i) : f
            else
              [*ai.dup, i].tap{ |t| stack << [t, ri.drop(1)] }
            end
          }
        end
      end
    end
  end
end

.tallyObject



21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/mll.rb', line 21

def tally
  lambda do |list, test = nil| # implement #sameq ?
    return Hash[ list.group_by{ |i| i }.map{ |k, v| [k, v.size] } ] unless test
    Hash.new{ 0 }.tap do |result|
      list.each do |item|
        result[
          list.find{ |key| test[key, item] }
        ] += 1
      end
    end
  end
end