Skip to content

Commit 47c690b

Browse files
Christophe DelordChristophe Delord
Christophe Delord
authored and
Christophe Delord
committed
functions F.mapt2a and F.mapk2a
map functions on tables that return arrays
1 parent 2109040 commit 47c690b

File tree

3 files changed

+58
-0
lines changed

3 files changed

+58
-0
lines changed

doc/F.md

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1011,6 +1011,22 @@ t:mapk(f)
10111011
> maps `f` to the keys and values of `t` and returns
10121012
> `{k1=f(k1, t[k1]), k2=f(k2, t[k2]), ...}`
10131013
1014+
``` lua
1015+
F.mapt2a(f, t)
1016+
t:mapt2a(f)
1017+
```
1018+
1019+
> maps `f` to the values of `t` and returns the array
1020+
> `{f(t[k1]), f(t[k2]), ...}`
1021+
1022+
``` lua
1023+
F.mapk2a(f, t)
1024+
t:mapk2a(f)
1025+
```
1026+
1027+
> maps `f` to the keys and the values of `t` and returns the array
1028+
> `{f(k1, t[k1]), f(k2, t[k2]), ...}`
1029+
10141030
``` lua
10151031
F.reverse(xs)
10161032
xs:reverse()

libluax/F/F.lua

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2322,6 +2322,42 @@ register2 "mapk" (function(f, t)
23222322
return setmetatable(t2, mt)
23232323
end)
23242324

2325+
--[[@@@
2326+
```lua
2327+
F.mapt2a(f, t)
2328+
t:mapt2a(f)
2329+
```
2330+
> maps `f` to the values of `t` and returns the array `{f(t[k1]), f(t[k2]), ...}`
2331+
@@@]]
2332+
2333+
register2 "mapt2a" (function(f, t)
2334+
local ys = {}
2335+
local i = 0
2336+
for _, v in F_pairs(t) do
2337+
i = i+1
2338+
ys[i] = f(v)
2339+
end
2340+
return setmetatable(ys, mt)
2341+
end)
2342+
2343+
--[[@@@
2344+
```lua
2345+
F.mapk2a(f, t)
2346+
t:mapk2a(f)
2347+
```
2348+
> maps `f` to the keys and the values of `t` and returns the array `{f(k1, t[k1]), f(k2, t[k2]), ...}`
2349+
@@@]]
2350+
2351+
register2 "mapk2a" (function(f, t)
2352+
local ys = {}
2353+
local i = 0
2354+
for k, v in F_pairs(t) do
2355+
i = i+1
2356+
ys[i] = f(k, v)
2357+
end
2358+
return setmetatable(ys, mt)
2359+
end)
2360+
23252361
--[[@@@
23262362
```lua
23272363
F.reverse(xs)

tests/luax-tests/F_test.lua

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -980,6 +980,12 @@ local function table_transformations()
980980
eq(F.mapk(h, t), {x="x:20",y="y:40",z="z:60"})
981981
eq(t:mapk(h), {x="x:20",y="y:40",z="z:60"})
982982

983+
eq(F.mapt2a(f, t), {20,40,60})
984+
eq(t:mapt2a(f), {20,40,60})
985+
986+
eq(F.mapk2a(h, t), {"x:20","y:40","z:60"})
987+
eq(t:mapk2a(h), {"x:20","y:40","z:60"})
988+
983989
eq(F.reverse(xs), {30,20,10})
984990
eq(xs:reverse(), {30,20,10})
985991

0 commit comments

Comments
 (0)