Cleaning up examples.

This commit is contained in:
Bruce Hill 2018-06-20 15:23:03 -07:00
parent d73cbf0aa5
commit 7761f715f7

View File

@ -364,74 +364,3 @@ say: best of [2,-3,4,-8] where %x has score (%x * %x)
multiplication. In addition to being more efficient, it's also more powerful and
flexible for the language to allow you to define syntax that manipulates expressions.
For example, list comprehensions can (and are) easily defined in Nomsu as:
parse [%expr for %key-var in %list] as
result of
%result <- []
for %key-var in %list
add %expr to %result
return %result
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
%double-nums <- ((2 * %num) for %num in [1,2,3,4,5])
# Naturally, Nomsu's macros are hygienic, so even though "%result" is used as a local
variable in the macro, there won't be any namespace collisions or confusion if you
use a different variable named "%result" as any (or all) of the arguments to the macro.
%result <- [1,2,3,4]
%result <- ((2*%result) for %result in %result)
assume: %result = [2,4,6,8]
# You'll find that in a lot places where a functional programmer would think to use a
lambda function, what they actually want to do is some metaprogramming. If you embrace
the metaprogramming from the start, then you can do a lot more powerful stuff.
# For example, you can define a loop that operates on recursive datastructures, but still
has all of the normal imperative control structures:
compile [stack for %var] to
Lua value "stack\(%var as lua id)"
parse [recurse on %sub as %super] as
add %sub to (stack for %super)
parse [for %var in recursive %iterable %body] as
with {(stack for %var): [%iterable]}
repeat while: (length of (stack for %var)) > 0
%var <- (remove index 1 from (stack for %var))
with {%val: %expr}
if: %val != (nil)
add %val to %result
%body
=== next %var ===
=== stop %var ===
~~~~~~~~~~~~~~~~
# This action iterates over a recursive structure, but it's written imperatively and it
can return early without traversing the whole tree.
action [tree %tree contains %val]
for %subtree in recursive %tree
if: %subtree = %val
return: yes
if: (type of %subtree) = "table"
for % in %subtree: recurse on % as %subtree
return: no
%t <- [1,[2,[3,4,[]],5,[6]]]
say: tree %t contains 3
say: tree %t contains 99
action [linked list from %list]
%head <- (nil)
for %i in (length of %list) to 1 via -1
%head <- {value:%list.%i, next:%head}
return %head
for %node in recursive (linked list from [3,4,5,6,7])
say "NODE: \(%node.value)"
recurse on %node.next as %node