git.s-ol.nu alive / a78d57b
add array/map s-ol 1 year, 14 days ago
2 changed file(s) with 53 addition(s) and 4 deletion(s). Raw diff Collapse all Expand all
511511 any = sig! / evt!
512512
513513 class extends PureOp
514 pattern: any*0
515 type: (args) => Array #args, args[1]\type!
514 pattern: any!*0
515 type: (args) =>
516 Array #args, args[1]\type!
516517
517518 tick: =>
518519 args = @unwrap_all!
0 import Array, Op, PureOp, Constant, Error, const, sig, evt from require 'alv.base'
1
0 import Array, Op, PureOp, Builtin, Constant, Error, const, sig, evt, T from require 'alv.base'
1 import Cell from require 'alv.cell'
2 import Tag from require 'alv.tag'
3 builtins = require 'alv.builtins'
4
5 unpack or= table.unpack
26 any = sig! / evt!
37
48 get = Constant.meta
235239
236240 @out\set out
237241
242 array_constr = builtins!\get('array').result
243 map = Constant.meta
244 meta:
245 name: 'map'
246 summary: "Apply an function to each value in an array."
247 examples: { '(map array fn)' }
248 description: "
249 Invokes `fn` once for each element in `array` and returns an array of the results.
250 `fn` must take one argument and return the same type consistently."
251
252 value: class extends Builtin
253 eval: (scope, tail) =>
254 L\trace "evaling #{@}"
255 assert #tail == 2, "'map' takes exactly two arguments"
256 tail = [L\push t\eval, scope for t in *tail]
257 { array, fn } = tail
258
259 fndef = fn.result
260 assert fn\type! == T.fndef, "fn has to be a fndef"
261 array_type = array\type!
262 assert array_type.__class == Array, Error 'argument', "expected an Array"
263
264 invocations = for i=1, array_type.size
265 tag_o = @tag\clone Tag.parse tostring i
266 tag_i = @tag\clone tag_o
267 Cell tag_o, {
268 with Constant.literal T.fndef, fndef!, 'fn'
269 .meta = fndef.meta
270 Cell tag_i, {
271 Constant.literal T.opdef, get!, 'get'
272 Constant.literal array_type, array.result!, 'array'
273 Constant.num i-1
274 }
275 }
276
277 tag = @tag\clone Tag.parse '-1'
278 inner = Cell tag, {
279 Constant.literal T.opdef, array_constr, 'array'
280 unpack invocations
281 }
282 super inner\eval scope
283
284
238285 Constant.meta
239286 meta:
240287 name: 'array'
244291 :get, :set
245292 :head, :tail, :prepend
246293 :insert, :remove
294 :map
247295
248296 :size, :concat