Data commit

This commit is contained in:
Ingy döt Net 2023-07-01 11:58:00 -04:00
parent 7387c8f97b
commit cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions

View file

@ -0,0 +1,2 @@
---
from: http://rosettacode.org/wiki/Extend_your_language

View file

@ -0,0 +1,32 @@
{{Control Structures}}
Some programming languages allow you to [[wp:Extensible_programming|extend]] the language. While this can be done to a certain degree in most languages (e.g. by using macros), other languages go much further. Most notably in the Forth and Lisp families, programming per se is done by extending the language without any formal distinction between built-in and user-defined elements.
If your language supports it, show how to introduce a new flow control mechanism. A practical and useful example is a four-way branch:
Occasionally, code must be written that depends on ''two'' conditions, resulting in up to four branches (depending on whether both, only the first, only the second, or none of the conditions are "true"). In a C-like language this could look like the following:
if (condition1isTrue) {
if (condition2isTrue)
bothConditionsAreTrue();
else
firstConditionIsTrue();
}
else if (condition2isTrue)
secondConditionIsTrue();
else
noConditionIsTrue();
Besides being rather cluttered, the statement(s) for 'condition2isTrue' must be written down twice. If 'condition2isTrue' were a lengthy and involved expression, it would be quite unreadable, and the code generated by the compiler might be unnecessarily large.
This can be improved by introducing a new keyword '''if2'''. It is similar to '''if''', but takes two conditional statements instead of one, and up to three 'else' statements. One proposal (in pseudo-C syntax) might be:
if2 (condition1isTrue) (condition2isTrue)
bothConditionsAreTrue();
else1
firstConditionIsTrue();
else2
secondConditionIsTrue();
else
noConditionIsTrue();
Pick the syntax which suits your language. The keywords 'else1' and 'else2' are just examples. The new conditional expression should look, nest and behave analogously to the language's built-in 'if' statement.

View file

@ -0,0 +1,24 @@
CMP_Double .macro ;NESASM3 syntax
; input:
; \1 = first condition. Valid addressing modes: immediate, zero page, or absolute.
; \2 = second condition. Valid addressing modes: immediate, zero page, or absolute.
; \3 = branch here if both are true
; \4 = branch here if only first condition is true
; \5 = branch here if only second condition is true
; \6 = branch here if both are false
CMP \1
BNE .check2\@ ;\1 is not true
CMP \2
BEQ .doubletrue\@
JMP \4 ;only condition 1 is true
.doubletrue\@:
JMP \3 ;both are true
.check2\@:
CMP \2
BNE .doublefalse\@
JMP \5 ;only condition 2 is true
.doublefalse:
JMP \6 ;both are false
.endm

View file

@ -0,0 +1,30 @@
macro if2_EQ_DOT_L 1,2,3,4
;input: 1 = first param (can be any addressing mode compatible with CMP)
; 2 = second param (used for condition 1)
; 3 = third param (used for condition 2)
; 4 = output for comparison results (must be a data register, and can't be 1, 2, or 3. The macro will not enforce this!)
; <backslash>@ represents a macro-local label that is scoped for each instance of that macro in your program
; and doesn't cause "label already defined" conflicts if the macro is used multiple times
MOVEQ #0,\4
CMP.L \2,\1
BEQ \@eqCond1
;condition 1 failed.
CMP.L \3,\1
BEQ \@TwoButNotOne
;both failed
clr.b d0
bra \@done
\@eqCond1:
CMP.L \3,\1
BEQ \@Both
move.b #2,d0
bra \@done
\@Both:
move.b #3,d0
bra \@done
\@TwoButNotOne:
move.b #1,d0
\@done:
endm

View file

@ -0,0 +1,4 @@
DATA(result) = COND #( WHEN condition1istrue = abap_true AND condition2istrue = abap_true THEN bothconditionsaretrue
WHEN condition1istrue = abap_true THEN firstconditionistrue
WHEN condition2istrue = abap_true THEN secondconditionistrue
ELSE noconditionistrue ).

View file

@ -0,0 +1,13 @@
# operator to turn two boolean values into an integer - name inspired by the COBOL sample #
PRIO ALSO = 1;
OP ALSO = ( BOOL a, b )INT: IF a AND b THEN 1 ELIF a THEN 2 ELIF b THEN 3 ELSE 4 FI;
# using the above operator, we can use the standard CASE construct to provide the #
# required construct, e.g.: #
BOOL a := TRUE, b := FALSE;
CASE a ALSO b
IN print( ( "both: a and b are TRUE", newline ) )
, print( ( "first: only a is TRUE", newline ) )
, print( ( "second: only b is TRUE", newline ) )
, print( ( "neither: a and b are FALSE", newline ) )
ESAC

View file

@ -0,0 +1,24 @@
begin
% executes pBoth, p1, p2 or pNeither %
% depending on whether c1 and c2 are true, c1 is true, c2 is true %
% neither c1 nor c2 are true %
procedure if2 ( logical value c1, c2
; procedure pBoth, p1, p2, pNeither
);
if c1 and c2 then pBoth
else if c1 then p1
else if c2 then p2
else pNeither
;
begin
logical a, b;
a := true;
b := false;
if2( a, b
, write( "both: a and b are TRUE" )
, write( "first: only a is TRUE" )
, write( "second: only b is TRUE" )
, write( "neither: a and b are FALSE" )
)
end
end.

View file

@ -0,0 +1,18 @@
(* Languages with pattern matching ALREADY HAVE THIS! *)
fn
func (pred1 : bool, pred2 : bool) : void =
case+ (pred1, pred2) of
| (true, true) => println! ("(true, true)")
| (true, false) => println! ("(true, false)")
| (false, true) => println! ("(false, true)")
| (false, false) => println! ("(false, false)")
implement
main0 () =
begin
func (true, true);
func (true, false);
func (false, true);
func (false, false)
end

View file

@ -0,0 +1,20 @@
with Ada.Text_IO; use Ada.Text_IO;
procedure Test_If_2 is
type Two_Bool is range 0 .. 3;
function If_2(Cond_1, Cond_2: Boolean) return Two_Bool is
(Two_Bool(2*Boolean'Pos(Cond_1)) + Two_Bool(Boolean'Pos(Cond_2)));
begin
for N in 10 .. 20 loop
Put(Integer'Image(N) & " is ");
case If_2(N mod 2 = 0, N mod 3 = 0) is
when 2#11# => Put_Line("divisible by both two and three.");
when 2#10# => Put_Line("divisible by two, but not by three.");
when 2#01# => Put_Line("divisible by three, but not by two.");
when 2#00# => Put_Line("neither divisible by two, nor by three.");
end case;
end loop;
end Test_If_2;

View file

@ -0,0 +1,16 @@
data Bool : Set where
true : Bool
false : Bool
if_then_else : {l} {A : Set l} -> Bool -> A -> A -> A
if true then t else e = t
if false then t else e = e
if2_,_then_else1_else2_else_ : {l} {A : Set l} -> (b1 b2 : Bool) -> (t e1 e2 e : A) -> A
if2 true , true then t else1 e1 else2 e2 else e = t
if2 true , false then t else1 e1 else2 e2 else e = e1
if2 false , true then t else1 e1 else2 e2 else e = e2
if2 false , false then t else1 e1 else2 e2 else e = e
example : Bool
example = if2 true , false then true else1 false else2 true else false

View file

@ -0,0 +1,26 @@
#include <jambo.h>
#defn Siambassonverdaderas(_X_,_Y_) ##CODEIF,__firstop__=0;#ATOM#CMPLX;cpy(__firstop__),\
__secondop__=0;#ATOM#CMPLX;cpy(__secondop__);\
and;jnt(#ENDIF),
#defn Essólolaprimeraopción jmp(%%CODEIF), %ENDIF:, {__firstop__}, jnt(#ENDIF),
#defn Essólolasegundaopción jmp(%%CODEIF), %ENDIF:, {__secondop__}, jnt(#ENDIF),
#synon Else Noesningunaopción?
#synon EndIf FindelSi
Main
False(v), True(w)
Si ambas son verdaderas ( v, w )
Printnl ("Son ambas opciones verdaderas")
Es sólo la primera opción
Printnl ("La primera opción es verdadera")
Es sólo la segunda opción
Printnl ("La segunda opción es verdadera")
No es ninguna opción?
Printnl ("Nada se cumple")
Fin del Si
End

View file

@ -0,0 +1,49 @@
#include <jambo.h>
#defn Sitodassonverdaderas(*) ##CODEIF,{1},#GENCODE $$$*$$$ opción#ITV=0;#ATCMLIST;\
cpy(opción#ITV);and;#ENDGEN;,jnt(#ENDIF)
#synon Sitodassonverdaderas Sitodaslasopciones,Sitodasestas,Sitodas
#defn Sonverdaderas(*) jmp(%%CODEIF), %ENDIF:, {1}, #GENCODE $$$*$$$ #ATCMLIST;\
and;#ENDGEN;jnt(#ENDIF),
#defn Esla(_X_) jmp(%%CODEIF), %ENDIF:, {_X_}, jnt(#ENDIF),
#defn Esverdaderalaopción(_X_) jmp(%%CODEIF), %ENDIF:, {opción_X_}, jnt(#ENDIF),
#defn Sonverdaderaslasopciones(*) jmp(%%CODEIF), %ENDIF:,{1};#GENCODE $$$*$$$ {opción#LIST};\
and;#ENDGEN;jnt(#ENDIF),
#synon Sonverdaderaslasopciones Sonlasopciones
#synon Else Noesningunaopción?
#synon EndIf FindelSi
#define verdadera? ;
#synon verdadera? verdaderas?,verdadera,verdaderas,sonverdaderas,esverdadera
Main
True(v), True(x), True(y)
Si todas estas 'v, {0.025} Is equal to (10), x, y' son verdaderas
Set ("Todas las opciones son verdaderas")
Son verdaderas 'opción 2, opción 3, opción 4'
Set ("Sólo son verdaderas la igualdad, X e Y")
Son verdaderas las opciones '1,3,4'
Set ("Son verdaderas V, X e Y")
Son las opciones '1,3,4' verdaderas?
Set ("Son verdaderas V, X e Y")
Son verdaderas 'opción 1, opción 3'
Set ("Son verdaderas V y X")
/* podríamos seguir preguntando... */
Es verdadera la opción '2'
Set ("Al menos, la igualdad es verdadera")
Es la 'opción 4' verdadera?
Set ("Al menos, Y es verdadera")
No es ninguna opción?
Set ("Nada se cumple")
Fin del Si
Prnl
End

View file

@ -0,0 +1,17 @@
#include <jambo.h>
Main
True(v), False(w), first option=0, second option=0
If ( var 'v' » 'first option', And ( w » 'second option' ) )
Printnl ("Son ambas opciones verdaderas")
Else If ( first option )
Printnl ("La primera opción es verdadera")
Else If ( second option )
Printnl ("La segunda opción es verdadera")
Else
Printnl ("Ninguna es verdadera")
End If
End

View file

@ -0,0 +1,12 @@
if2: function [cond1 cond2 both one two none][
case []
when? [and? cond1 cond2] -> do both
when? [cond1] -> do one
when? [cond2] -> do two
else -> do none
]
if2 false true [print "both"]
[print "only first"]
[print "only second"]
[print "none"]

View file

@ -0,0 +1,126 @@
using System;
using System.Reflection;
namespace Extend_your_language
{
class Program
{
public static void Main(string[] args)
{
Console.WriteLine();
Console.WriteLine("Hello World!");
Console.WriteLine();
int x = 0;
int y = 0;
for(x=0;x<2;x++)
{
for(y=0;y<2;y++)
{
CONDITIONS( (x==0) , (y==0) ).
IF2 ("METHOD1").
ELSE1("METHOD2").
ELSE2("METHOD3").
ELSE ("METHOD4");
}
}
Console.WriteLine();
Console.Write("Press any key to continue . . . ");
Console.ReadKey(true);
}
public static void METHOD1()
{
Console.WriteLine("METHOD 1 executed - both are true");
}
public static void METHOD2()
{
Console.WriteLine("METHOD 2 executed - first is true");
}
public static void METHOD3()
{
Console.WriteLine("METHOD 3 executed - second is true");
}
public static void METHOD4()
{
Console.WriteLine("METHOD 4 executed - both are false");
}
static int CONDITIONS(bool condition1, bool condition2)
{
int c = 0;
if(condition1 && condition2)
c = 0;
else if(condition1)
c = 1;
else if(condition2)
c = 2;
else
c = 3;
return c;
}
}
public static class ExtensionMethods
{
public static int IF2(this int value, string method)
{
if(value == 0)
{
MethodInfo m = typeof(Program).GetMethod(method);
m.Invoke(null,null);
}
return value;
}
public static int ELSE1(this int value, string method)
{
if(value == 1)
{
MethodInfo m = typeof(Program).GetMethod(method);
m.Invoke(null,null);
}
return value;
}
public static int ELSE2(this int value, string method)
{
if(value == 2)
{
MethodInfo m = typeof(Program).GetMethod(method);
m.Invoke(null,null);
}
return value;
}
public static void ELSE(this int value, string method)
{
if(value == 3)
{
MethodInfo m = typeof(Program).GetMethod(method);
m.Invoke(null,null);
}
}
}
}

View file

@ -0,0 +1,16 @@
/* Four-way branch.
*
* if2 (firsttest, secondtest
* , bothtrue
* , firstrue
* , secondtrue
* , bothfalse
* )
*/
#define if2(firsttest,secondtest,bothtrue,firsttrue,secondtrue,bothfalse)\
switch(((firsttest)?0:2)+((secondtest)?0:1)) {\
case 0: bothtrue; break;\
case 1: firsttrue; break;\
case 2: secondtrue; break;\
case 3: bothfalse; break;\
}

View file

@ -0,0 +1,24 @@
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include "if2.h"
int main(int argc, char *argv[]) {
int i;
for (i = 1; i < argc; i++) {
char *arg= argv[i], *ep;
long lval = strtol(arg, &ep, 10); /* convert arg to long */
if2 (arg[0] == '\0', *ep == '\0'
, puts("empty string")
, puts("empty string")
, if2 (lval > 10, lval > 100
, printf("%s: a very big number\n", arg)
, printf("%s: a big number\n", arg)
, printf("%s: a very big number\n", arg)
, printf("%s: a number\n", arg)
)
, printf("%s: not a number\n", arg)
)
}
return 0;
}

View file

@ -0,0 +1,9 @@
$ make exten && ./exten 3 33 333 3a b " " -2
cc exten.c -o exten
3: a number
33: a big number
333: a very big number
3a: not a number
b: not a number
: not a number
-2: a number

View file

@ -0,0 +1,34 @@
#include <stdio.h>
#define if2(a, b) switch(((a)) + ((b)) * 2) { case 3:
#define else00 break; case 0: /* both false */
#define else10 break; case 1: /* true, false */
#define else01 break; case 2: /* false, true */
#define else2 break; default: /* anything not metioned */
#define fi2 } /* stupid end bracket */
int main()
{
int i, j;
for (i = 0; i < 3; i++) for (j = 0; j < 3; j++) {
printf("%d %d: ", i, j);
if2 (i == 1, j == 1)
printf("both\n");
else10
printf("left\n");
else01
printf("right\n");
else00 { /* <-- bracket is optional, flaw */,
printf("neither\n");
if2 (i == 2, j == 2)
printf("\tis 22");
printf("\n"); /* flaw: this is part of if2! */
else2
printf("\tnot 22\n");
fi2
}
fi2
}
return 0;
}

View file

@ -0,0 +1,10 @@
EVALUATE EXPRESSION-1 ALSO EXPRESSION-2
WHEN TRUE ALSO TRUE
DISPLAY 'Both are true.'
WHEN TRUE ALSO FALSE
DISPLAY 'Expression 1 is true.'
WHEN FALSE ALSO TRUE
DISPLAY 'Expression 2 is true.'
WHEN OTHER
DISPLAY 'Neither is true.'
END-EVALUATE

View file

@ -0,0 +1,15 @@
alias if2(cond1:Bool,
cond2:Bool,
both,
first,
second,
neither)
{
var res1 = cond1;
var res2 = cond2;
if (res1 and res2) return both;
if (res1) return first;
if (res2) return second;
return neither;
}

View file

@ -0,0 +1,5 @@
(defmacro if2 [[cond1 cond2] bothTrue firstTrue secondTrue else]
`(let [cond1# ~cond1
cond2# ~cond2]
(if cond1# (if cond2# ~bothTrue ~firstTrue)
(if cond2# ~secondTrue ~else))))

View file

@ -0,0 +1,7 @@
(defmacro if2
[cond1 cond2 both-true first-true second-true both-false]
`(case [~cond1 ~cond2]
[true true] ~both-true,
[true false] ~first-true,
[false true] ~second-true
[false false] ~both-false))

View file

@ -0,0 +1,9 @@
(defmacro if2 (cond1 cond2 both first second &rest neither)
(let ((res1 (gensym))
(res2 (gensym)))
`(let ((,res1 ,cond1)
(,res2 ,cond2))
(cond ((and ,res1 ,res2) ,both)
(,res1 ,first)
(,res2 ,second)
(t ,@neither)))))

View file

@ -0,0 +1 @@
Notation "A /\ B" := (and A B)

View file

@ -0,0 +1,32 @@
void if2(T1, T2, T3, T4)(in bool c1, in bool c2,
lazy T1 first,
lazy T2 both,
lazy T3 second,
lazy T4 none) {
if (c1) {
if (c2)
both;
else
first;
} else {
if (c2)
second;
else
none;
}
}
void test(in bool a, in bool b) {
import std.stdio;
if2(a, b, writeln("first"),
writeln("both"),
writeln("second"),
writeln("none"));
}
void main() {
test(1 < 2, 3 > 4);
test(1 < 2, 1 < 2);
test(3 > 4, 3 > 4);
test(3 > 4, 1 < 2);
}

View file

@ -0,0 +1,4 @@
{two-conditional if operator implementation}
{ [ top cond. = true ][ top cond. = false ]}
{ [ 2nd = true ][2nd = false ] [ 2nd = true ][ 2nd = false] }
[(((([[)))!)))%%%%%][)))))!)%%%%%]?][[))))!))%%%%%][))))))!%%%%%]?]?]⇒¿

View file

@ -0,0 +1 @@
0 1_['t,'t,]['t,'f,]['f,'t,]['f,'f,]¿

View file

@ -0,0 +1,15 @@
procedure Check(Condition1: Boolean; Condition2: Boolean)
begin
if Condition1 = True then
begin
if Condition2 = True then
BothConditionsAreTrue
else
FirstConditionIsTrue;
end
else
if Condition2 = True then
SecondConditionIsTrue
else
NoConditionIsTrue;
end;

View file

@ -0,0 +1,10 @@
procedure Check(Condition1: Boolean; Condition2: Boolean)
begin
if (Condition1 = True) and (Condition2 = True) then
BothConditionsAreTrue
else if Condition1 = True then
FirstConditionIsTrue
else if Condition2 = True then
SecondConditionIsTrue
else NoConditionIsTrue;
end;

View file

@ -0,0 +1,44 @@
pragma.enable("lambda-args") # The feature is still experimental syntax
def makeIf2Control(evalFn, tf, ft, ff) {
return def if2Control {
to only1__control_0(tf) { return makeIf2Control(evalFn, tf, ft, ff) }
to only2__control_0(ft) { return makeIf2Control(evalFn, tf, ft, ff) }
to else__control_0 (ff) { return makeIf2Control(evalFn, tf, ft, ff) }
to run__control() {
def [[a :boolean, b :boolean], # Main parameters evaluated
tt # First block ("then" case)
] := evalFn()
return (
if (a) { if (b) {tt} else {tf} } \
else { if (b) {ft} else {ff} }
)()
}
}
}
def if2 {
# The verb here is composed from the keyword before the brace, the number of
# parameters in the parentheses, and the number of parameters after the
# keyword.
to then__control_2_0(evalFn) {
# evalFn, when called, evaluates the expressions in parentheses, then
# returns a pair of those expressions and the first { block } as a
# closure.
return makeIf2Control(evalFn, fn {}, fn {}, fn {})
}
}
for a in [false,true] {
for b in [false,true] {
if2 (a, b) then {
println("both")
} only1 {
println("a true")
} only2 {
println("b true")
} else {
println("neither")
}
}
}

View file

@ -0,0 +1,11 @@
if2.then__control_2_0(fn {
[[a, b], fn {
println("both")
}]
}).only1__control_0(fn {
println("a true")
}).only2__control_0(fn {
println("b true")
}).else__control_0(fn {
println("neither")
}).run__control()

View file

@ -0,0 +1,23 @@
(define-syntax-rule
(if2 cond1 cond2 both cond1-only cond2-only none) ;; new syntax
;; will expand to :
(if cond1
(if cond2 both cond1-only)
(if cond2 cond2-only none)))
→ #syntax:if2
(define (num-test n)
(if2 (positive? n) (exact? n)
"positive and exact"
"positive and inexact"
"negative and exact"
"negative and inexact"))
(num-test 3/4)
→ "positive and exact"
(num-test -666)
→ "negative and exact"
(num-test -666.42)
→ "negative and inexact"
(num-test PI)
→ "positive and inexact"

View file

@ -0,0 +1,9 @@
(defmacro if2 (cond1 cond2 both first second &rest neither)
(let ((res1 (gensym))
(res2 (gensym)))
`(let ((,res1 ,cond1)
(,res2 ,cond2))
(cond ((and ,res1 ,res2) ,both)
(,res1 ,first)
(,res2 ,second)
(t ,@neither)))))

View file

@ -0,0 +1,9 @@
fn if2 cond1 cond2 body11 body10 body01 body00 {
# Must evaluate both conditions, and should do so in order.
# Negation ensures a boolean result: a true condition becomes
# 1 for false; a false condition becomes 0 for true.
let (c1 = <={! $cond1}; c2 = <={! $cond2}) {
# Use those values to pick the body to evaluate.
$(body$c1$c2)
}
}

View file

@ -0,0 +1,9 @@
if2 {test 1 -gt 0} {~ grill foo bar boo} {
echo 1 and 2
} {
echo 1 but not 2
} {
echo 2 but not 1
} {
echo neither 1 nor 2
}

View file

@ -0,0 +1,22 @@
// Extend your language. Nigel Galloway: September 14th., 2021
type elsetf=TF
type elseft=FT
type elseff=FF
let elsetf,elseft,elseff=TF,FT,FF
let if2 n g tt (TF:elsetf)tf (FT:elseft)ft (FF:elseff)ff=match(n,g) with (true,true)->tt() |(true,false)->tf() |(false,true)->ft() |_->ff()
if2 (13<23) (23<42) (fun()->printfn "tt")
elsetf (fun()->printfn "tf")
elseft (fun()->printfn "ft")
elseff (fun()->printfn "ff")
if2 (13<23) (42<23) (fun()->printfn "tt")
elsetf (fun()->printfn "tf")
elseft (fun()->printfn "ft")
elseff (fun()->printfn "ff")
if2 (23<23) (23<42) (fun()->printfn "tt")
elsetf (fun()->printfn "tf")
elseft (fun()->printfn "ft")
elseff (fun()->printfn "ff")
if2 (23<13) (42<23) (fun()->printfn "tt")
elsetf (fun()->printfn "tf")
elseft (fun()->printfn "ft")
elseff (fun()->printfn "ff")

View file

@ -0,0 +1,4 @@
if2 (13<23) (23<42) (fun()->printfn "tt")
elseff (fun()->printfn "tf")
elseft (fun()->printfn "ft")
elseff (fun()->printfn "ff")

View file

@ -0,0 +1,4 @@
if2 (13<23) (42<23) (fun()->printfn "tt")
elsetx (fun()->printfn "tf")
elseft (fun()->printfn "ft")
elseff (fun()->printfn "ff")

View file

@ -0,0 +1,4 @@
( scratchpad ) : 2ifte ( ..a ?0 ?1 quot0: ( ..a -- ..b ) quot1: ( ..a -- ..b ) quot2: ( ..a -- ..b ) quot3: ( ..a -- ..b ) -- ..b )
[ [ if ] curry curry ] 2bi@ if ; inline
( scratchpad ) 3 [ 0 > ] [ even? ] bi [ 0 ] [ 1 ] [ 2 ] [ 3 ] 2ifte .
2

View file

@ -0,0 +1,18 @@
;; Fennel, being a Lisp, provides a way to define macros for new syntax.
;; The "`" and "," characters are used to construct a template for the macro.
(macro if2 [cond1 cond2 both first second none]
`(if ,cond1
(if ,cond2 ,both ,first)
(if ,cond2 ,second ,none)))
(fn test-if2 [x y]
(if2 x y
(print "both")
(print "first")
(print "second")
(print "none")))
(test-if2 true true) ;"both"
(test-if2 true false) ;"first"
(test-if2 false true) ;"second"
(test-if2 false false) ;"none"

View file

@ -0,0 +1,14 @@
\ in this construct, either of the ELSE clauses may be omitted, just like IF-THEN.
: BOTH postpone IF postpone IF ; immediate
: ORELSE postpone THEN postpone ELSE postpone IF ; immediate
: NEITHER postpone THEN postpone THEN ; immediate
: fb ( n -- )
dup 5 mod 0= over 3 mod 0=
BOTH ." FizzBuzz "
ELSE ." Fizz "
ORELSE ." Buzz "
ELSE dup .
NEITHER drop ;
: fizzbuzz ( n -- ) 0 do i 1+ fb loop ;

View file

@ -0,0 +1,51 @@
LOGICAL A,B !These are allocated the same storage
INTEGER IA,IB !As the default integer size.
EQUIVALENCE (IA,A),(IB,B) !So, this will cause no overlaps.
WRITE (6,*) "Boolean tests via integers..."
DO 199 IA = 0,1 !Two states for A.
DO 199 IB = 0,1 !Two states for B.
IF (IA) 666,99,109 !Not four ways, just three.
99 IF (IB) 666,100,101 !Negative values are surely wrong.
100 WRITE (6,*) "FF",IA,IB
GO TO 199
101 WRITE (6,*) "FT",IA,IB
GO TO 199
109 IF (IB) 666,110,111 !A second test.
110 WRITE (6,*) "TF",IA,IB
GO TO 199
111 WRITE (6,*) "TT",IA,IB
199 CONTINUE !Both loops finish here.
WRITE (6,*) "Boolean tests via integers and computed GO TO..."
DO 299 IA = 0,1 !Two states for A.
DO 299 IB = 0,1 !Two states for B.
GO TO (200,201,210,211) 1 + IA*2 + IB !Counting starts with one.
200 WRITE (6,*) "FF",IA,IB
GO TO 299
201 WRITE (6,*) "FT",IA,IB
GO TO 299
210 WRITE (6,*) "TF",IA,IB
GO TO 299
211 WRITE (6,*) "TT",IA,IB
299 CONTINUE !Both loops finish here.
300 WRITE (6,301)
301 FORMAT (/,"Boolean tests via LOGICAL variables...",/
1 " AB IA IB (IA*2 + IB)")
A = .TRUE. !Syncopation.
B = .TRUE. !Via the .NOT., the first pair will be FF.
DO I = 0,1 !Step through two states.
A = .NOT.A !Thus generate F then T.
DO J = 0,1 !Step through the second two states.
B = .NOT.B !Thus generate FF, FT, TF, TT.
WRITE (6,302) A,B,IA,IB,IA*2 + IB !But with strange values.
302 FORMAT (1X,2L1,2I6,I8) !Show both types.
END DO !Next value for B.
END DO !Next value for A.
GO TO 999
666 WRITE (6,*) "Huh?"
999 CONTINUE
END

View file

@ -0,0 +1,6 @@
INTEGER FUNCTION IF2(A,B) !Combine two LOGICAL variables.
LOGICAL A,B !These.
IF2 = 0 !Wasted effort if A is true.
IF (A) IF2 = 2 !But it avoids IF ... THEN ... ELSE ... END IF blather.
IF (B) IF2 = IF2 + 1 !This relies on IF2 being a variable. (Standard in F90+)
END FUNCTION IF2 !Thus produce a four-way result.

View file

@ -0,0 +1,6 @@
SELECT CASE(IF2(A,B))
CASE(B"00"); WRITE (6,*) "Both false."
CASE(B"01"); WRITE (6,*) "B only."
CASE(B"10"); WRITE (6,*) "A only."
CASE(B"11"); WRITE (6,*) "Both true."
END SELECT

View file

@ -0,0 +1,24 @@
program fourWay(input, output, stdErr);
var
tuple: record
A: boolean;
B: char;
end;
begin
tuple.A := true;
tuple.B := 'Z';
case tuple of
(A: false; B: 'R'):
begin
writeLn('R is not good');
end;
(A: true; B: 'Z'):
begin
writeLn('Z is great');
end;
else
begin
writeLn('No');
end;
end;
end.

View file

@ -0,0 +1,32 @@
' FB 1.05.0 Win64
#Macro If2(condition1, condition2)
#Define Else1 ElseIf CBool(condition1) Then
#Define Else2 ElseIf CBool(condition2) Then
If CBool(condition1) AndAlso CBool(condition2) Then
#Endmacro
Sub test(a As Integer, b As Integer)
If2(a > 0, b > 0)
print "both positive"
Else1
print "first positive"
Else2
print "second positive"
Else
print "neither positive"
End If
End Sub
Dim As Integer a, b
Print "a = 1, b = 1 => ";
test(1, 1)
Print "a = 1, b = 0 => ";
test(1, 0)
Print "a = 0, b = 1 => ";
test(0, 1)
Print "a = 0, b = 0 => ";
test(0, 0)
Print
Print "Press any key to quit"
Sleep

View file

@ -0,0 +1,58 @@
package main
import "fmt"
type F func()
type If2 struct {cond1, cond2 bool}
func (i If2) else1(f F) If2 {
if i.cond1 && !i.cond2 {
f()
}
return i
}
func (i If2) else2(f F) If2 {
if i.cond2 && !i.cond1 {
f()
}
return i
}
func (i If2) else0(f F) If2 {
if !i.cond1 && !i.cond2 {
f()
}
return i
}
func if2(cond1, cond2 bool, f F) If2 {
if cond1 && cond2 {
f()
}
return If2{cond1, cond2}
}
func main() {
a, b := 0, 1
if2 (a == 1, b == 3, func() {
fmt.Println("a = 1 and b = 3")
}).else1 (func() {
fmt.Println("a = 1 and b <> 3")
}).else2 (func() {
fmt.Println("a <> 1 and b = 3")
}).else0 (func() {
fmt.Println("a <> 1 and b <> 3")
})
// It's also possible to omit any (or all) of the 'else' clauses or to call them out of order
a, b = 1, 0
if2 (a == 1, b == 3, func() {
fmt.Println("a = 1 and b = 3")
}).else0 (func() {
fmt.Println("a <> 1 and b <> 3")
}).else1 (func() {
fmt.Println("a = 1 and b <> 3")
})
}

View file

@ -0,0 +1,7 @@
if2 :: Bool -> Bool -> a -> a -> a -> a -> a
if2 p1 p2 e12 e1 e2 e =
if p1 then
if p2 then e12 else e1
else if p2 then e2 else e
main = print $ if2 True False (error "TT") "TF" (error "FT") (error "FF")

View file

@ -0,0 +1,20 @@
procedure main(A)
if2 { (A[1] = A[2]), (A[3] = A[4]), # Use PDCO with all three else clauses
write("1: both true"),
write("1: only first true"),
write("1: only second true"),
write("1: neither true")
}
if2 { (A[1] = A[2]), (A[3] = A[4]), # Use same PDCO with only one else clause
write("2: both true"),
write("2: only first true"),
}
end
procedure if2(A) # The double-conditional PDCO
suspend if @A[1] then
if @A[2] then |@A[3] # Run-err if missing 'then' clause
else @\A[4] # (all else clauses are optional)
else if @A[2] then |@\A[5]
else |@\A[6]
end

View file

@ -0,0 +1,5 @@
if2 : Bool -> Bool -> Lazy a -> Lazy a -> Lazy a -> Lazy a -> a
if2 True True v _ _ _ = v
if2 True False _ v _ _ = v
if2 False True _ _ v _ = v
if2 _ _ _ _ _ v = v

View file

@ -0,0 +1,4 @@
To if2 (c1 - condition) and-or (c2 - condition) begin -- end: (- switch (({c1})*2 + ({c2})) { 3: do -).
To else1 -- in if2: (- } until (1); 2: do { -).
To else2 -- in if2: (- } until (1); 1: do { -).
To else0 -- in if2: (- } until (1); 0: -).

View file

@ -0,0 +1,12 @@
Home is a room.
When play begins:
if2 (the player is in Home) and-or (the player is a person) begin;
say "both";
else1;
say "only 1";
else2;
say "only 2";
else0;
say "neither";
end if2.

View file

@ -0,0 +1,6 @@
To say if2 (c1 - condition) and-or (c2 - condition) -- beginning if2:
(- switch (({c1})*2 + ({c2})) { 3: -).
To say else1 -- continuing if2: (- 2: -).
To say else2 -- continuing if2: (- 1: -).
To say else0 -- continuing if2: (- 0: -).
To say end if2 -- ending if2: (- } -).

View file

@ -0,0 +1,4 @@
Home is a room.
When play begins:
say "[if2 the player is not in Home and-or the player is not a person]both[else1]only 1[else2]only 2[else0]neither[end if2]".

View file

@ -0,0 +1,4 @@
if2=: 2 :0
'`b1 b2'=. n
m@.(b1 + 2 * b2) f.
)

View file

@ -0,0 +1,14 @@
f0=: [: smoutput 'neither option: ' , ":
f1=: [: smoutput 'first option: ' , ":
f2=: [: smoutput 'second option: ' , ":
f3=: [: smoutput 'both options: ' , ":
isprime=: 1&p:
iseven=: 0 = 2&|
f0`f1`f2`f3 if2 (isprime`iseven)"0 i.5
second option: 0
neither option: 1
both options: 2
first option: 3
second option: 4

View file

@ -0,0 +1,13 @@
public class If2 {
public static void if2(boolean firstCondition, boolean secondCondition,
Runnable bothTrue, Runnable firstTrue, Runnable secondTrue, Runnable noneTrue) {
if (firstCondition)
if (secondCondition)
bothTrue.run();
else firstTrue.run();
else if (secondCondition)
secondTrue.run();
else noneTrue.run();
}
}

View file

@ -0,0 +1,15 @@
import static If2.if2;
class Main {
private static void print(String s) {
System.out.println(s);
}
public static void main(String[] args) {
// prints "both true"
if2(true, true,
() -> print("both true"),
() -> print("first true"),
() -> print("second true"),
() -> print("none true"));
}
}

View file

@ -0,0 +1,41 @@
public class If2 {
private final boolean firstCondition;
private final boolean secondCondition;
public If2(boolean firstCondition, boolean secondCondition) {
this.firstCondition = firstCondition;
this.secondCondition = secondCondition;
}
public static If2 if2(boolean firstCondition, boolean secondCondition) {
return new If2(firstCondition, secondCondition);
}
public If2 then(Runnable runnable) {
if (firstCondition && secondCondition) {
runnable.run();
}
return this;
}
public If2 elseNone(Runnable runnable) {
if (!firstCondition && !secondCondition) {
runnable.run();
}
return this;
}
public If2 elseIfFirst(Runnable runnable) {
if (firstCondition && !secondCondition) {
runnable.run();
}
return this;
}
public If2 elseIfSecond(Runnable runnable) {
if (!firstCondition && secondCondition) {
runnable.run();
}
return this;
}
}

View file

@ -0,0 +1,14 @@
// prints "both true"
if2(true, true)
.then(() -> print("both true"))
.elseIfFirst(() -> print("first true"))
.elseIfSecond(() -> print("second true"))
.elseNone(() -> print("none true"));
// if we only care about both true and none true...
// prints "none true"
if2(false, false)
.then(() -> print("both true"))
.elseNone(() -> { // a lambda can have a block body
print("none true");
});

View file

@ -0,0 +1,6 @@
def if2($c1; $c2; both; first; second; neither):
if $c1 and $c2 then both
elif $c1 then first
elif $c2 then second
else neither
end;

View file

@ -0,0 +1,8 @@
def if2(c1; c2; both; first; second; neither):
c1 as $c1
| c2 as $c2
| if $c1 and $c2 then both
elif $c1 then first
elif $c2 then second
else neither
end;

View file

@ -0,0 +1,91 @@
const CSTACK1 = Array{Bool,1}()
const CSTACK2 = Array{Bool,1}()
const CSTACK3 = Array{Bool,1}()
macro if2(condition1, condition2, alltrue)
if !(length(CSTACK1) == length(CSTACK2) == length(CSTACK3))
throw("prior if2 statement error: must have if2, elseif1, elseif2, and elseifneither")
end
ifcond1 = eval(condition1)
ifcond2 = eval(condition2)
if ifcond1 && ifcond2
eval(alltrue)
push!(CSTACK1, false)
push!(CSTACK2, false)
push!(CSTACK3, false)
elseif ifcond1
push!(CSTACK1, true)
push!(CSTACK2, false)
push!(CSTACK3, false)
elseif ifcond2
push!(CSTACK1, false)
push!(CSTACK2, true)
push!(CSTACK3, false)
else
push!(CSTACK1, false)
push!(CSTACK2, false)
push!(CSTACK3, true)
end
end
macro elseif1(block)
quote
if pop!(CSTACK1)
$block
end
end
end
macro elseif2(block)
quote
if pop!(CSTACK2)
$block
end
end
end
macro elseifneither(block)
quote
if pop!(CSTACK3)
$block
end
end
end
# Testing of code starts here
@if2(2 != 4, 3 != 7, begin x = "all"; println(x) end)
@elseif1(begin println("one") end)
@elseif2(begin println("two") end)
@elseifneither(begin println("neither") end)
@if2(2 != 4, 3 == 7, println("all"))
@elseif1(begin println("one") end)
@elseif2(begin println("two") end)
@elseifneither(begin println("neither") end)
@if2(2 == 4, 3 != 7, begin x = "all"; println(x) end)
@elseif1(begin println("one") end)
@elseif2(begin println("two") end)
@elseifneither(begin println("neither") end)
@if2(2 == 4, 3 == 7, println("last all") end)
@elseif1(begin println("one") end)
@elseif2(begin println("two") end)
@elseifneither(begin println("neither") end)

View file

@ -0,0 +1,53 @@
// version 1.0.6
data class IfBoth(val cond1: Boolean, val cond2: Boolean) {
fun elseFirst(func: () -> Unit): IfBoth {
if (cond1 && !cond2) func()
return this
}
fun elseSecond(func: () -> Unit): IfBoth {
if (cond2 && !cond1) func()
return this
}
fun elseNeither(func: () -> Unit): IfBoth {
if (!cond1 && !cond2) func()
return this // in case it's called out of order
}
}
fun ifBoth(cond1: Boolean, cond2: Boolean, func: () -> Unit): IfBoth {
if (cond1 && cond2) func()
return IfBoth(cond1, cond2)
}
fun main(args: Array<String>) {
var a = 0
var b = 1
ifBoth (a == 1, b == 3) {
println("a = 1 and b = 3")
}
.elseFirst {
println("a = 1 and b <> 3")
}
.elseSecond {
println("a <> 1 and b = 3")
}
.elseNeither {
println("a <> 1 and b <> 3")
}
// It's also possible to omit any (or all) of the 'else' clauses or to call them out of order
a = 1
b = 0
ifBoth (a == 1, b == 3) {
println("a = 1 and b = 3")
}
.elseNeither {
println("a <> 1 and b <> 3")
}
.elseFirst {
println("a = 1 and b <> 3")
}
}

View file

@ -0,0 +1,18 @@
{macro \{if2 (true|false|\{[^{}]*\}) (true|false|\{[^{}]*\})\}
to {if {and $1 $2}
then both are true
else {if {and $1 {not $2}}
then the first is true
else {if {and {not $1} $2}
then the second is true
else neither are true}}}}
{if2 true true} -> both are true
{if2 true false} -> the first is true
{if2 false true} -> the second is true
{if2 false false} -> neither are true
{if2 {< 1 2} {< 3 4}} -> both are true
{if2 {< 1 2} {> 3 4}} -> the first is true
{if2 {> 1 2} {< 3 4}} -> the second is true
{if2 {> 1 2} {> 3 4}} -> neither are true

View file

@ -0,0 +1,6 @@
given .x nxor, .y nxor {
case true: ... # both true
case true, false: ... # first true, second false
case false, true: ... # first false, second true
default: ... # both false
}

View file

@ -0,0 +1,7 @@
given .x, .y {
case true: ... # both true
case true, false: ... # first true, second false
case false, true: ... # first false, second true
case null, _: ... # first null, second irrelevant
default: ... # other
}

View file

@ -0,0 +1,23 @@
// Create a type to handle the captures
define if2 => type {
data private a, private b
public oncreate(a,b) => {
.a = #a
.b = #b
thread_var_push(.type,self)
handle => { thread_var_pop(.type)}
return givenblock()
}
public ifboth => .a && .b ? givenblock()
public else1 => .a && !.b ? givenblock()
public else2 => !.a && .b ? givenblock()
public else => !.a && !.b ? givenblock()
}
// Define methods to consider givenblocks
define ifboth => thread_var_get(::if2)->ifboth => givenblock
define else1 => thread_var_get(::if2)->else1 => givenblock
define else2 => thread_var_get(::if2)->else2 => givenblock
define else => thread_var_get(::if2)->else => givenblock

View file

@ -0,0 +1,14 @@
if2(true,true) => {
ifboth => {
bothConditionsAreTrue
}
else1 => {
firstConditionIsTrue
}
else2 => {
secondConditionIsTrue
}
else => {
noConditionIsTrue
}
}

View file

@ -0,0 +1,41 @@
-- Extend your language, in Lua, 6/17/2020 db
-- not to be taken seriously, ridiculous, impractical, esoteric, obscure, arcane ... but it works
-------------------
-- IMPLEMENTATION:
-------------------
function if2(cond1, cond2)
return function(code)
code = code:gsub("then2", "[3]=load[[")
code = code:gsub("else1", "]],[2]=load[[")
code = code:gsub("else2", "]],[1]=load[[")
code = code:gsub("neither", "]],[0]=load[[")
code = "return {" .. code .. "]]}"
local block, err = load(code)
if (err) then error("syntax error in if2 statement: "..err) end
local tab = block()
tab[(cond1 and 2 or 0) + (cond2 and 1 or 0)]()
end
end
----------
-- TESTS:
----------
for i = 1, 2 do
for j = 1, 2 do
print("i="..i.." j="..j)
if2 ( i==1, j==1 )[[ then2
print("both conditions are true")
else1
print("first is true, second is false")
else2
print("first is false, second is true")
neither
print("both conditions are false")
]]
end
end

View file

@ -0,0 +1,39 @@
module if2 {
over 3 : read &c
c=not (stackitem() and stackitem(2))
}
module ifelse1 {
over 3 : read &c
c=not (stackitem() and not stackitem(2))
}
module ifelse2 {
over 3 : read &c
c=not (stackitem(2) and not stackitem())
}
module ifelse {
over 3 : read &c
c=stackitem() or stackitem(2)
}
module endif2 {
if not empty then drop 3
}
ctrl=true
for a=1 to 2
for b=1 to 2
Print "a=";a, "b=";b
if2 a=1, b=2, &ctrl : Part {
print "both", a, b
} as ctrl
ifelse1 : Part {
print "first", a
} as ctrl
ifelse2 : Part {
print "second", b
} as ctrl
ifelse : part {
print "no one"
} as ctrl
endif2
next b
next a
Print "ok"

View file

@ -0,0 +1,21 @@
divert(-1)
#
# m4 is a macro language, so this is just a matter of defining a
# macro, using the built-in branching macro "ifelse".
#
# ifelse2(x1,x2,y1,y2,exprxy,exprx,expry,expr)
#
# Checks if x1 and x2 are equal strings and if y1 and y2 are equal
# strings.
#
define(`ifelse2',
`ifelse(`$1',`$2',`ifelse(`$3',`$4',`$5',`$6')',
`ifelse(`$3',`$4',`$7',`$8')')')
divert`'dnl
dnl
ifelse2(1,1,2,2,`exprxy',`exprx',`expry',`expr')
ifelse2(1,1,2,-2,`exprxy',`exprx',`expry',`expr')
ifelse2(1,-1,2,2,`exprxy',`exprx',`expry',`expr')
ifelse2(1,-1,2,-2,`exprxy',`exprx',`expry',`expr')

View file

@ -0,0 +1,9 @@
If2[test1_, test2_, condBoth_, cond1_, cond2_, condNone_] := With[
{result1 = test1,
result2 = test2},
Which[
result1 && result2, condBoth,
result1, cond1,
result2, cond2,
True, condNone]];
SetAttributes[If2, HoldAll];

View file

@ -0,0 +1,5 @@
x = 0;
If2[Mod[(++x), 2] == 0, Mod[x, 3] == 1, Print["Both: ", x], Print["First: ", x], Print["Second: ", x], Print["Neither: ", x]];
If2[Mod[(++x), 2] == 0, Mod[x, 3] == 1, Print["Both: ", x], Print["First: ", x], Print["Second: ", x], Print["Neither: ", x]];
If2[Mod[(++x), 2] == 0, Mod[x, 3] == 1, Print["Both: ", x], Print["First: ", x], Print["Second: ", x], Print["Neither: ", x]];
If2[Mod[(++x), 2] == 0, Mod[x, 3] == 1, Print["Both: ", x], Print["First: ", x], Print["Second: ", x], Print["Neither: ", x]];

View file

@ -0,0 +1,22 @@
(
:none :two :one :both -> :r2 -> :r1
(
((r1 r2 and)(both))
((r1)(one))
((r2)(two))
((true)(none))
) case
) :if2
(3 4 >) (0 0 ==)
("both are true")
("the first is true")
("the second is true")
("both are false")
if2 puts! ;the second is true
;compare to regular if
(4 even?)
("true")
("false")
if puts! ;true

View file

@ -0,0 +1,77 @@
import morfa.base;
// introduce 4 new operators to handle the if2 syntax
operator then { kind = infix, precedence = mul, associativity = right}
operator else1 { kind = infix, precedence = not, associativity = left }
operator else2 { kind = infix, precedence = not, associativity = left }
operator none { kind = infix, precedence = not, associativity = left }
// function which bounds the condition expression to the if2 "actions"
public func then(condition: IF2.Condition, actionHolder: IF2): void
{
actionHolder.actions[condition]();
}
// functions (bound to operators) used to "build" the if2 "statement"
public func else1(bothAction: func(): void, else1Action: func(): void): IF2
{
return IF2([IF2.Condition.both -> bothAction,
IF2.Condition.else1 -> else1Action]);
}
public func else2(actionHolder: IF2, action: func(): void): IF2
{
return checkAndAdd(actionHolder, action, IF2.Condition.else2);
}
public func none(actionHolder: IF2, action: func(): void): IF2
{
return checkAndAdd(actionHolder, action, IF2.Condition.none);
}
// finally, function which combines two conditions into a "trigger" for the if2 "statement"
public func if2(condition1: bool, condition2: bool): IF2.Condition
{
if (condition1 and condition2)
return IF2.Condition.both;
else if (condition1)
return IF2.Condition.else1;
else if (condition2)
return IF2.Condition.else2;
else
return IF2.Condition.none;
}
// private helper function to build the IF2 structure
func checkAndAdd(actionHolder: IF2, action: func(): void, actionName: IF2.Condition): IF2
{
if (actionHolder.actions.contains(actionName))
throw new Exception("action defined twice for one condition in if2");
else
actionHolder.actions[actionName] = action;
return actionHolder;
}
// helper structure to process the if2 "statement"
struct IF2
{
public enum Condition { both, else1, else2, none };
public var actions: Dict<Condition, func(): void>;
}
// usage
if2 (true, false) then func()
{
println("both true");
}
else1 func()
{
println("first true");
}
else2 func()
{
println("second true");
}
none func()
{
println("none true");
};

View file

@ -0,0 +1,12 @@
// point of interest: the when keyword and && operator inside the macro definition are macros themselves
macro if2 (cond1, cond2, bodyTT, bodyTF, bodyFT, bodyFF)
syntax ("if2", "(", cond1, ")", "(", cond2, ")", bodyTT, "elseTF", bodyTF, "elseFT", bodyFT, "else", bodyFF)
{
<[
when($cond1 && $cond2) {$bodyTT};
when($cond1 && !($cond2)) {$bodyTF};
when(!($cond1) && $cond2) {$bodyFT};
when(!($cond1) && !($cond2)) {$bodyFF};
]>
}

View file

@ -0,0 +1,20 @@
using System;
using System.Console;
module UseIf2
{
Main() : void
{
def happy = true;
def knowit = false;
if2 (happy) (knowit)
Write("Clap hands")
elseTF
Write("You're happy")
elseFT
Write("Cheer up")
else
Write("You're unhappy, cheer up");
}
}

View file

@ -0,0 +1,23 @@
(context 'if2)
(define-macro (if2:if2 cond1 cond2 both-true first-true second-true neither)
(cond
((eval cond1)
(if (eval cond2)
(eval both-true)
(eval first-true)))
((eval cond2)
(eval second-true))
(true
(eval neither))))
(context MAIN)
> (if2 true true 'bothTrue 'firstTrue 'secondTrue 'else)
bothTrue
> (if2 true false 'bothTrue 'firstTrue 'secondTrue 'else)
firstTrue
> (if2 false true 'bothTrue 'firstTrue 'secondTrue 'else)
secondTrue
> (if2 false false 'bothTrue 'firstTrue 'secondTrue 'else)
else

View file

@ -0,0 +1,62 @@
import macros
proc newIfElse(c, t, e: NimNode): NimNode {.compiletime.} =
result = newIfStmt((c, t))
result.add(newNimNode(nnkElse).add(e))
macro if2(x, y: bool; z: untyped): untyped =
var parts: array[4, NimNode]
for i in parts.low .. parts.high:
parts[i] = newNimNode(nnkDiscardStmt).add(NimNode(nil))
assert z.kind == nnkStmtList
assert z.len <= 4
for i in 0 ..< z.len:
assert z[i].kind == nnkCall
assert z[i].len == 2
var j = 0
case $z[i][0]
of "then": j = 0
of "else1": j = 1
of "else2": j = 2
of "else3": j = 3
else: assert false
parts[j] = z[i][1].last
result = newIfElse(x,
newIfElse(y, parts[0], parts[1]),
newIfElse(y, parts[2], parts[3]))
if2 2 > 1, 3 < 2:
then:
echo "1"
else1:
echo "2"
else2:
echo "3"
else3:
echo "4"
# Missing cases are supported:
if2 2 > 1, 3 < 2:
then:
echo "1"
else2:
echo "3"
else3:
echo "4"
# Order can be swapped:
if2 2 > 1, 3 < 2:
then:
echo "1"
else2:
echo "3"
else1:
echo "2"
else3:
echo "4"

View file

@ -0,0 +1,13 @@
(* Languages with pattern matching ALREADY HAVE THIS! *)
let myfunc pred1 pred2 =
match (pred1, pred2) with
| (true, true) -> print_endline ("(true, true)");
| (true, false) -> print_endline ("(true, false)");
| (false, true) -> print_endline ("(false, true)");
| (false, false) -> print_endline ("(false, false)");;
myfunc true true;;
myfunc true false;;
myfunc false true;;
myfunc false false;;

View file

@ -0,0 +1,7 @@
if2(c1,c2,tt,tf,ft,ff)={
if(c1,
if(c2,tt,tf)
,
if(c2,ft,ff)
)
};

View file

@ -0,0 +1,14 @@
GEN
if2(GEN c1, GEN c2, GEN tt, GEN tf, GEN ft, GEN ff)
{
if (gequal0(c1))
if (gequal0(c2))
return ff ? closure_evalgen(ff) : gnil;
else
return ft ? closure_evalgen(ft) : gnil;
else
if (gequal0(c2))
return tf ? closure_evalgen(tf) : gnil;
else
return tt ? closure_evalgen(tt) : gnil;
}

View file

@ -0,0 +1,2 @@
install("if2","GGDEDEDEDE","if2","./if2.gp.so");
addhelp(if2, "if2(a,b,{seq1},{seq2},{seq3},{seq4}): if a is nonzero and b is nonzero, seq1 is evaluated; if a is nonzero and b is zero, seq2 is evaluated; if a is zero and b is nonzero, seq3 is evaluated; otherwise seq4. seq1 through seq4 are optional.");

View file

@ -0,0 +1,4 @@
/*
GP;install("if2","GGDEDEDEDE","if2","./if2.gp.so");
GP;addhelp(if2, "if2(a,b,{seq1},{seq2},{seq3},{seq4}): if a is nonzero and b is nonzero, seq1 is evaluated; if a is nonzero and b is zero, seq2 is evaluated; if a is zero and b is nonzero, seq3 is evaluated; otherwise seq4. seq1 through seq4 are optional.");
*/

View file

@ -0,0 +1,53 @@
module stmts;
import phl::lang::io;
/* LinkedList --> Each element contains a condition */
struct @ConditionalChain {
field @Boolean cond;
field @ConditionalChain next;
@ConditionalChain init(@Boolean cond, @ConditionalChain next) [
this::cond = cond;
this::next = next;
return this;
]
/*
* If the condition is true executes the closure and returns a false element, otherwise returns the next condition
*
* Execution starts from the first element, and iterates until the right element is found.
*/
@ConditionalChain then(@Closure<@Void> closure) [
if (isNull(next())) return new @ConditionalChain.init(false, null);
if (cond()) {
closure();
return new @ConditionalChain.init(false, null);
}
else return next();
]
/* Operators create a cool look */
@ConditionalChain operator then(@Closure<@Void> closure) alias @ConditionalChain.then;
@ConditionalChain operator else1(@Closure<@Void> closure) alias @ConditionalChain.then;
@ConditionalChain operator else2(@Closure<@Void> closure) alias @ConditionalChain.then;
@ConditionalChain operator orElse(@Closure<@Void> closure) alias @ConditionalChain.then;
};
/* Returns linked list [a && b, a, b, true] */
@ConditionalChain if2(@Boolean a, @Boolean b) [
return new @ConditionalChain.init(a && b, new @ConditionalChain.init(a, new @ConditionalChain.init(b, new @ConditionalChain.init(true, null))));
]
@Void main [
if2(false, true) then [
println("Not this!");
] else1 [
println("Not this!");
] else2 [
println("This!");
] orElse [
println("Not this!");
];
]

View file

@ -0,0 +1,134 @@
#!/usr/bin/perl
use warnings;
use strict;
use v5.10;
=for starters
Syntax:
if2 condition1, condition2, then2 {
# both conditions are true
}
else1 {
# only condition1 is true
}
else2 {
# only condition2 is true
}
orelse {
# neither condition is true
};
Any (but not all) of the `then' and `else' clauses can be omitted, and else1
and else2 can be specified in either order.
This extension is imperfect in several ways:
* A normal if-statement uses round brackets, but this syntax forbids them.
* Perl doesn't have a `then' keyword; if it did, it probably wouldn't be
preceded by a comma.
* Unless it's the last thing in a block, the whole structure must be followed
by a semicolon.
* Error messages appear at runtime, not compile time, and they don't show the
line where the user's syntax error occurred.
We could solve most of these problems with a source filter, but those are
dangerous. Can anyone else do better? Feel free to improve or replace.
=cut
# All the new `keywords' are in fact functions. Most of them return lists
# of four closures, one of which is then executed by if2. Here are indexes into
# these lists:
use constant {
IdxThen => 0,
IdxElse1 => 1,
IdxElse2 => 2,
IdxOrElse => 3
};
# Most of the magic is in the (&) prototype, which lets a function accept a
# closure marked by nothing except braces.
sub orelse(&) {
my $clause = shift;
return undef, undef, undef, $clause;
}
sub else2(&@) {
my $clause = shift;
die "Can't have two `else2' clauses"
if defined $_[IdxElse2];
return (undef, $_[IdxElse1], $clause, $_[IdxOrElse]);
}
sub else1(&@) {
my $clause = shift;
die "Can't have two `else1' clauses"
if defined $_[IdxElse1];
return (undef, $clause, $_[IdxElse2], $_[IdxOrElse]);
}
sub then2(&@) {
die "Can't have two `then2' clauses"
if defined $_[1+IdxThen];
splice @_, 1+IdxThen, 1;
return @_;
}
# Here, we collect the two conditions and four closures (some of which will be
# undefined if some clauses are missing). We work out which of the four
# clauses (closures) to call, and call it if it exists.
use constant {
# Defining True and False is almost always bad practice, but here we
# have a valid reason.
True => (0 == 0),
False => (0 == 1)
};
sub if2($$@) {
my $cond1 = !!shift; # Convert to Boolean to guarantee matching
my $cond2 = !!shift; # against either True or False
die "if2 must be followed by then2, else1, else2, &/or orelse"
if @_ != 4
or grep {defined and ref $_ ne 'CODE'} @_;
my $index;
if (!$cond1 && !$cond2) {$index = IdxOrElse}
if (!$cond1 && $cond2) {$index = IdxElse2 }
if ( $cond1 && !$cond2) {$index = IdxElse1 }
if ( $cond1 && $cond2) {$index = IdxThen }
my $closure = $_[$index];
&$closure if defined $closure;
}
# This is test code. You can play with it by deleting up to three of the
# four clauses.
sub test_bits($) {
(my $n) = @_;
print "Testing $n: ";
if2 $n & 1, $n & 2, then2 {
say "Both bits 0 and 1 are set";
}
else1 {
say "Only bit 0 is set";
}
else2 {
say "Only bit 1 is set";
}
orelse {
say "Neither bit is set";
}
}
test_bits $_ for 0 .. 7;

View file

@ -0,0 +1,10 @@
msl@64Lucid:~/perl$ ./if2
Testing 0: Neither bit is set
Testing 1: Only bit 0 is set
Testing 2: Only bit 1 is set
Testing 3: Both bits 0 and 1 are set
Testing 4: Neither bit is set
Testing 5: Only bit 0 is set
Testing 6: Only bit 1 is set
Testing 7: Both bits 0 and 1 are set
msl@64Lucid:~/perl$

View file

@ -0,0 +1,8 @@
(phixonline)-->
<span style="color: #008080;">switch</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">condition1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">condition2</span><span style="color: #0000FF;">}</span> <span style="color: #008080;">do</span>
<span style="color: #008080;">case</span> <span style="color: #0000FF;">{</span><span style="color: #004600;">true</span><span style="color: #0000FF;">,</span><span style="color: #004600;">true</span><span style="color: #0000FF;">}:</span>
<span style="color: #008080;">case</span> <span style="color: #0000FF;">{</span><span style="color: #004600;">true</span><span style="color: #0000FF;">,</span><span style="color: #004600;">false</span><span style="color: #0000FF;">}:</span>
<span style="color: #008080;">case</span> <span style="color: #0000FF;">{</span><span style="color: #004600;">false</span><span style="color: #0000FF;">,</span><span style="color: #004600;">true</span><span style="color: #0000FF;">}:</span>
<span style="color: #008080;">case</span> <span style="color: #0000FF;">{</span><span style="color: #004600;">false</span><span style="color: #0000FF;">,</span><span style="color: #004600;">false</span><span style="color: #0000FF;">}:</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">switch</span>
<!--

View file

@ -0,0 +1,12 @@
(phixonline)-->
<span style="color: #008080;">function</span> <span style="color: #000000;">if2</span><span style="color: #0000FF;">(</span><span style="color: #004080;">bool</span> <span style="color: #000000;">c1</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">bool</span> <span style="color: #000000;">c2</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">c1</span><span style="color: #0000FF;">*</span><span style="color: #000000;">10</span><span style="color: #0000FF;">+</span><span style="color: #000000;">c2</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">switch</span> <span style="color: #000000;">if2</span><span style="color: #0000FF;">(</span><span style="color: #000000;">condition1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">condition2</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<span style="color: #008080;">case</span> <span style="color: #000000;">11</span><span style="color: #0000FF;">:</span>
<span style="color: #008080;">case</span> <span style="color: #000000;">10</span><span style="color: #0000FF;">:</span>
<span style="color: #008080;">case</span> <span style="color: #000000;">01</span><span style="color: #0000FF;">:</span>
<span style="color: #008080;">case</span> <span style="color: #000000;">00</span><span style="color: #0000FF;">:</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">switch</span>
<!--

View file

@ -0,0 +1,14 @@
(phixonline)-->
<span style="color: #008080;">enum</span> <span style="color: #000000;">BOTH</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0b11</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">FIRST</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0b10</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">SECOND</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0b01</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">NEITHER</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0b00</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">if2</span><span style="color: #0000FF;">(</span><span style="color: #004080;">bool</span> <span style="color: #000000;">c1</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">bool</span> <span style="color: #000000;">c2</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">c1</span><span style="color: #0000FF;">*</span><span style="color: #000000;">2</span><span style="color: #0000FF;">+</span><span style="color: #000000;">c2</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">r</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">if2</span><span style="color: #0000FF;">(</span><span style="color: #000000;">condition1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">condition2</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">r</span><span style="color: #0000FF;">=</span><span style="color: #000000;">BOTH</span> <span style="color: #008080;">then</span>
<span style="color: #008080;">elsif</span> <span style="color: #000000;">r</span><span style="color: #0000FF;">=</span><span style="color: #000000;">FIRST</span> <span style="color: #008080;">then</span>
<span style="color: #008080;">elsif</span> <span style="color: #000000;">r</span><span style="color: #0000FF;">=</span><span style="color: #000000;">SECOND</span> <span style="color: #008080;">then</span>
<span style="color: #008080;">elsif</span> <span style="color: #000000;">r</span><span style="color: #0000FF;">=</span><span style="color: #000000;">NEITHER</span> <span style="color: #008080;">then</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<!--

View file

@ -0,0 +1,5 @@
(phixonline)-->
<span style="color: #008080;">global</span> <span style="color: #008080;">constant</span> <span style="color: #000000;">T_if2</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">5200</span> <span style="color: #000000;">tt_stringF</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"if2"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">T_if2</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">global</span> <span style="color: #008080;">constant</span> <span style="color: #000000;">T_else1</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">5200</span> <span style="color: #000000;">tt_stringF</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"else1"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">T_else1</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">global</span> <span style="color: #008080;">constant</span> <span style="color: #000000;">T_else2</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">5200</span> <span style="color: #000000;">tt_stringF</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"else2"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">T_else2</span><span style="color: #0000FF;">)</span>
<!--

View file

@ -0,0 +1,4 @@
(phixonline)-->
<span style="color: #000080;font-style:italic;">--constant T_endelseelsif = {T_end,T_else,T_elsif,T_case,T_default,T_fallthru,T_fallthrough}</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">T_endelseelsif</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">T_end</span><span style="color: #0000FF;">,</span><span style="color: #000000;">T_else</span><span style="color: #0000FF;">,</span><span style="color: #000000;">T_else1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">T_else2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">T_elsif</span><span style="color: #0000FF;">,</span><span style="color: #000000;">T_case</span><span style="color: #0000FF;">,</span><span style="color: #000000;">T_default</span><span style="color: #0000FF;">,</span><span style="color: #000000;">T_fallthru</span><span style="color: #0000FF;">,</span><span style="color: #000000;">T_fallthrough</span><span style="color: #0000FF;">}</span>
<!--

View file

@ -0,0 +1,3 @@
(phixonline)-->
<span style="color: #008080;">elsif</span> <span style="color: #000000;">ttidx</span><span style="color: #0000FF;">=</span><span style="color: #000000;">T_if2</span> <span style="color: #008080;">then</span> <span style="color: #000000;">DoIf2</span><span style="color: #0000FF;">()</span>
<!--

View file

@ -0,0 +1,14 @@
(phixonline)-->
<span style="color: #008080;">for</span> <span style="color: #000000;">N</span><span style="color: #0000FF;">=</span><span style="color: #000000;">10</span> <span style="color: #008080;">to</span> <span style="color: #000000;">20</span> <span style="color: #008080;">do</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%d is "</span><span style="color: #0000FF;">,</span><span style="color: #000000;">N</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">if2</span> <span style="color: #7060A8;">mod</span><span style="color: #0000FF;">(</span><span style="color: #000000;">N</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)=</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #7060A8;">mod</span><span style="color: #0000FF;">(</span><span style="color: #000000;">N</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">)=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"divisible by both two and three.\n"</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">else1</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"divisible by two, but not by three.\n"</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">else2</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"divisible by three, but not by two.\n"</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">else</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"neither divisible by two, nor by three.\n"</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #000000;">if2</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--

View file

@ -0,0 +1,8 @@
(undef 'if2) # Undefine the built-in 'if2'
(de if2 "P"
(if (eval (pop '"P"))
(eval ((if (eval (car "P")) cadr caddr) "P"))
(if (eval (car "P"))
(eval (cadddr "P"))
(run (cddddr "P")) ) ) )

View file

@ -0,0 +1,13 @@
\def\iftwo#1#2#3#4#5\elsefirst#6\elsesecond#7\elseneither#8\owtfi
{\if#1#2\if#3#4#5\else#6\fi\else\if#3#4#7\else#8\fi\fi}
\def\both{***both***}
\def\first{***first***}
\def\second{***second***}
\def\neither{***neither***}
\message{\iftwo{1}{1}{2}{2}\both\elsefirst\first\elsesecond\second\elseneither\neither\owtfi}
\message{\iftwo{1}{1}{2}{-2}\both\elsefirst\first\elsesecond\second\elseneither\neither\owtfi}
\message{\iftwo{1}{-1}{2}{2}\both\elsefirst\first\elsesecond\second\elseneither\neither\owtfi}
\message{\iftwo{1}{-1}{2}{-2}\both\elsefirst\first\elsesecond\second\elseneither\neither\owtfi}
\bye

View file

@ -0,0 +1,47 @@
function When-Condition
{
[CmdletBinding()]
Param
(
[Parameter(Mandatory=$true, Position=0)]
[bool]
$Test1,
[Parameter(Mandatory=$true, Position=1)]
[bool]
$Test2,
[Parameter(Mandatory=$true, Position=2)]
[scriptblock]
$Both,
[Parameter(Mandatory=$true, Position=3)]
[scriptblock]
$First,
[Parameter(Mandatory=$true, Position=4)]
[scriptblock]
$Second,
[Parameter(Mandatory=$true, Position=5)]
[scriptblock]
$Neither
)
if ($Test1 -and $Test2)
{
return (&$Both)
}
elseif ($Test1 -and -not $Test2)
{
return (&$First)
}
elseif (-not $Test1 -and $Test2)
{
return (&$Second)
}
else
{
return (&$Neither)
}
}

View file

@ -0,0 +1,6 @@
When-Condition -Test1 (Test-Path .\temp.txt) -Test2 (Test-Path .\tmp.txt) `
-Both { "both true"
} -First { "first true"
} -Second { "second true"
} -Neither { "neither true"
}

Some files were not shown because too many files have changed in this diff Show more