【Janet】控制流
Janet 只有两种内建原语在函数内改变执行流。首先是 if 表达式,它的行为与其他语言一样。它有两或三个参数:一个条件,一个条件为真(不是 nil 或 false)时执行的表达式,一个条件为 nil 或 false 时执行的表达式。如果省略可选的表达式,默认为 nil 。
(if (> 4 3)"4 is greater than 3""4 is not greater then three") # Evaluates to the first statement(if true(print "Hey")) # Will print(if false(print "Oy!")) # Will not print
第二个控制流原语是 while 循环。 while 表达式也和大多数语言一样,包括 C,Java 和 Python。 while 循环接受两个或多个参数:首先是一个条件(像 if 一样),条件在每次迭代前检查。当条件为 nil 或 false 时, while 循环结束并返回 nil 。否则其余的参数会按顺序执行,然后程序回到循环的开始。
# Loop from 100 down to 1 and print each time
(var i 100)
(while (pos? i)(print "the number is " i)(-- i))# Print ... until a random number in range [0, 1) is >= 0.9
# (math/random evaluates to a value between 0 and 1)
(while (> 0.9 (math/random))(print "..."))
除了这些表达式,Janet 还有很多更适合大多数场景的用于条件测试和循环的宏。对于条件测试,可以使用 cond, case 和 when 宏。 cond 可以用来实现一个 if-else 链,只使用 if 表达式会导致很多括号。 case 类似于 C 里面的 switch ,但是不会自动 fall-through。 when 也类似 if ,但是当条件为 nil 或 false 时返回 false,和 Common Lisp 与 Clojure 中的 when 宏一样。对于循环, loop, seq 和 generate 实现了 Janet 中的列表推导,和 Python 或 Clojure 中一样。
