diff options
Diffstat (limited to 'spec/inputs/macro.moon')
-rw-r--r-- | spec/inputs/macro.moon | 69 |
1 files changed, 69 insertions, 0 deletions
diff --git a/spec/inputs/macro.moon b/spec/inputs/macro.moon new file mode 100644 index 0000000..eb1e224 --- /dev/null +++ b/spec/inputs/macro.moon | |||
@@ -0,0 +1,69 @@ | |||
1 | macro block init = -> | ||
2 | with require "moonp" | ||
3 | package.moonpath = "?.moon;./spec/inputs/?.moon" | ||
4 | "" | ||
5 | |||
6 | $init! | ||
7 | |||
8 | import "macro_export" as {$myconfig:$config, :$showMacro, :$asserts, :$assert} | ||
9 | |||
10 | $asserts item == nil | ||
11 | |||
12 | $myconfig false | ||
13 | |||
14 | v = $assert item == nil | ||
15 | |||
16 | macro expr and = (...)-> | ||
17 | values = [value for value in *{...}] | ||
18 | $showMacro "and", "#{ table.concat values, " and " }" | ||
19 | |||
20 | if $and f1 | ||
21 | print "OK" | ||
22 | |||
23 | if $and f1,f2,f3 | ||
24 | print "OK" | ||
25 | |||
26 | macro expr map = (items,action)-> | ||
27 | $showMacro "map", "[#{action} for _ in *#{items}]" | ||
28 | |||
29 | macro expr filter = (items,action)-> | ||
30 | $showMacro "filter", "[_ for _ in *#{items} when #{action}]" | ||
31 | |||
32 | macro expr reduce = (items,def,action)-> | ||
33 | $showMacro "reduce", "if ##{items} == 0 | ||
34 | #{def} | ||
35 | else | ||
36 | _1 = #{def} | ||
37 | for _2 in *#{items} | ||
38 | _1 = #{action} | ||
39 | _1" | ||
40 | |||
41 | macro block foreach = (items,action)-> | ||
42 | $showMacro "foreach", "for _ in *#{items} | ||
43 | #{action}" | ||
44 | |||
45 | macro expr pipe = (...)-> | ||
46 | switch select "#",... | ||
47 | when 0 then return "" | ||
48 | when 1 then return ... | ||
49 | ops = {...} | ||
50 | last = ops[1] | ||
51 | stmts = for i = 2,#ops | ||
52 | stmt = "\tlocal _#{i} = #{last} |> #{ops[i]}" | ||
53 | last = "_#{i}" | ||
54 | stmt | ||
55 | res = "do | ||
56 | #{table.concat stmts,"\n"} | ||
57 | #{last}" | ||
58 | $showMacro "pipe", res | ||
59 | |||
60 | {1,2,3} |> $map(_ * 2) |> $filter(_ > 4) |> $foreach print _ | ||
61 | |||
62 | $foreach $filter($map({1,2,3}, _ * 2), _ > 4), print _ | ||
63 | |||
64 | print $pipe( | ||
65 | {1, 2, 3} | ||
66 | $map(_ * 2) | ||
67 | $filter(_ > 4) | ||
68 | $reduce(0, _1 + _2) | ||
69 | ) | ||