From d22b685b0135e0e36fa02b9e0f4336c6893d0b0f Mon Sep 17 00:00:00 2001
From: Marshall Lochbaum
The useful control structures introduced here are collected as shortened definitions below.
If ← {𝕏⍟𝕎@}´ # Also Repeat -IfElse ← {c‿F‿T: c◶T‿F@} +IfElse ← {c‿T‿F: c◶F‿T@} While ← {𝕨{𝕊∘𝔾⍟𝔽𝕩}𝕩@}´ # While 1‿{... to run forever DoWhile ← {𝕨{𝕊⍟𝔽𝔾𝕩}𝕩@}´ For ← {I‿C‿P‿A: I@ ⋄ {𝕊∘P∘A⍟C 𝕩}@} @@ -60,7 +60,7 @@If-Else
Despite the name, an if-else statement is most closely related to a switch-case statement: in fact, it's just a special case where the two cases are true (
1) and false (0). As a result, we can implement it either with Choose (◶) or with case headers of1and0.When using Choose, note that the natural ordering places the false case before the true one to match list index ordering. To get the typical if-else order, the condition should be negated or the statements reversed. Here's a function to get an if-else statement by swapping the conditions, and two ways its application might be written.
-IfElse ← {cond‿False‿True: cond◶True‿False @} +IfElse ← {cond‿True‿False: cond◶False‿True @} IfElse ⟨𝕩<mid⊑𝕨 {𝕤⋄ hi↩mid} @@ -84,7 +84,7 @@Chained If-Else
One pattern in imperative languages is to check one condition and apply an action if it succeeds, but check a different condition if it fails, in sequence until some condition succeeds or every one has been checked. Languages might make this pattern easier by making if-else right associative, so that the programmer can write an
ifstatement followed by a sequence ofelse if"statements", or might just provide a unifiedelifkeyword that works similarly (while this is a common pattern, I suspect it's used more often than it's really wanted because of this syntactic support).In BQN it's possible to nest
-IfElseexpressions, but it's also possible to write a control structure that chains them all at one level. For this statement the input will be a sequence of⟨Test,Action⟩pairs, followed by a final action to perform if no test succeeds. The first test is always performed; other tests should be wrapped in blocks because otherwise they'll be executed even if an earlier test succeeded.Test ← {fn←{Cond‿Act 𝕊 else: Cond◶Act‿Else}´𝕩 ⋄ Fn@} +Test ← {fn←{Cond‿Act 𝕊 else: Cond◶Else‿Act}´𝕩 ⋄ Fn@} Test ⟨ ( a<b)‿{𝕤⋄a+↩1} -- cgit v1.2.3