Inverted syntax: Difference between revisions

Content added Content deleted
m (→‎{{header|Haskell}}: extended examples)
m (syntax highlighting fixup automation)
Line 5: Line 5:
In traditional syntax conditional expressions are usually shown before the action within a statement or code block:
In traditional syntax conditional expressions are usually shown before the action within a statement or code block:


<lang pseudocode> IF raining=true THEN needumbrella=true </lang>
<syntaxhighlight lang="pseudocode"> IF raining=true THEN needumbrella=true </syntaxhighlight>


In inverted syntax, the action is listed before the conditional expression in the statement or code block:
In inverted syntax, the action is listed before the conditional expression in the statement or code block:


<lang pseudocode> needumbrella=true IF raining=true </lang>
<syntaxhighlight lang="pseudocode"> needumbrella=true IF raining=true </syntaxhighlight>


'''Inverted syntax with assignment'''
'''Inverted syntax with assignment'''
Line 15: Line 15:
In traditional syntax, assignments are usually expressed with the variable appearing before the expression:
In traditional syntax, assignments are usually expressed with the variable appearing before the expression:


<lang pseudocode> a = 6</lang>
<syntaxhighlight lang="pseudocode"> a = 6</syntaxhighlight>


In inverted syntax, the expression appears before the variable:
In inverted syntax, the expression appears before the variable:
<lang pseudocode> 6 = a</lang>
<syntaxhighlight lang="pseudocode"> 6 = a</syntaxhighlight>


'''Task'''
'''Task'''
Line 29: Line 29:


The below example will result in an assemble time error. The intended action is that the X variable is decremented, and execution returns to the top of the loop. However, the branch is simply too far away.
The below example will result in an assemble time error. The intended action is that the X variable is decremented, and execution returns to the top of the loop. However, the branch is simply too far away.
<lang 6502asm>loop_MySubroutine:
<syntaxhighlight lang="6502asm">loop_MySubroutine:
; more than 127 bytes of code
; more than 127 bytes of code


dex
dex
bne loop_MySubroutine ;assembler will display an error message that the branch is too far away.
bne loop_MySubroutine ;assembler will display an error message that the branch is too far away.
; rest of program</lang>
; rest of program</syntaxhighlight>


The easiest way to overcome this limitation is to invert the branch condition and place a <code>JMP</code> back to the loop under it.
The easiest way to overcome this limitation is to invert the branch condition and place a <code>JMP</code> back to the loop under it.
An unconditional <code>JMP</code> moves the program counter to the specified location, no matter where that is.
An unconditional <code>JMP</code> moves the program counter to the specified location, no matter where that is.


<lang 6502asm>loop_mySubroutine:
<syntaxhighlight lang="6502asm">loop_mySubroutine:
; more than 127 bytes of code
; more than 127 bytes of code


Line 46: Line 46:
JMP loop_mySubroutine
JMP loop_mySubroutine
continue:
continue:
; rest of program</lang>
; rest of program</syntaxhighlight>


Now, what happens is that the opposite condition is checked. If X = 0, execution branches 3 bytes forward to "continue." Otherwise, the statement underneath the branch is executed, which is a jump back to the top.
Now, what happens is that the opposite condition is checked. If X = 0, execution branches 3 bytes forward to "continue." Otherwise, the statement underneath the branch is executed, which is a jump back to the top.
Line 52: Line 52:
===16-Bit Data===
===16-Bit Data===
Being a little-endian CPU, the "low byte" (rightmost 2 digits) of a 16-bit (4-digit) hexadecimal number is stored <i>before</i> the "high byte" (leftmost 2 digits). This is difficult for a human to read but easier for the CPU. The assembler allows the programmer to use a <code>dw</code> or <code>word</code> directive to define 16-bit data values in a manner easier for a person to read. The assembler swaps the order of the bytes automatically when assembling the source code.
Being a little-endian CPU, the "low byte" (rightmost 2 digits) of a 16-bit (4-digit) hexadecimal number is stored <i>before</i> the "high byte" (leftmost 2 digits). This is difficult for a human to read but easier for the CPU. The assembler allows the programmer to use a <code>dw</code> or <code>word</code> directive to define 16-bit data values in a manner easier for a person to read. The assembler swaps the order of the bytes automatically when assembling the source code.
<lang 6502asm>word $BEEF
<syntaxhighlight lang="6502asm">word $BEEF
byte $EF,$BE</lang>
byte $EF,$BE</syntaxhighlight>
A hexdump of these bytes would display them the same, i.e.: <pre>EF BE EF BE</pre>
A hexdump of these bytes would display them the same, i.e.: <pre>EF BE EF BE</pre>


Line 60: Line 60:
The only place where syntax is kind of inverted is <code>exit when</code> to exit loops:
The only place where syntax is kind of inverted is <code>exit when</code> to exit loops:


<lang Ada>Foo := 1;
<syntaxhighlight lang="ada">Foo := 1;
loop
loop
exit when Foo = 10;
exit when Foo = 10;
Foo := Foo + 1;
Foo := Foo + 1;
end loop;</lang>
end loop;</syntaxhighlight>


=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
{{works with|ALGOL 68G|Any - tested with release 2.8.win32}}
{{works with|ALGOL 68G|Any - tested with release 2.8.win32}}
<lang algol68># Inverted assignment #
<syntaxhighlight lang="algol68"># Inverted assignment #
# Assignment in Algol 68 is via ":=" which is automaically provided for all modes (types) #
# Assignment in Algol 68 is via ":=" which is automaically provided for all modes (types) #
# However we could define e.g. "=:" as an inverted assignment operator but we would need to #
# However we could define e.g. "=:" as an inverted assignment operator but we would need to #
Line 96: Line 96:


( VOID: print( ( "NO", newline ) ) ) WHEN a = b; # the anonymous PROC VOID is not called #
( VOID: print( ( "NO", newline ) ) ) WHEN a = b; # the anonymous PROC VOID is not called #
( VOID: print( ( "yes", newline ) ) ) WHEN a /= b # the anonymous PROC VOID is called #</lang>
( VOID: print( ( "yes", newline ) ) ) WHEN a /= b # the anonymous PROC VOID is called #</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 106: Line 106:
Typically, instructions with a destination register and a source register will have the leftmost register be the destination and the registers to the right be the source.
Typically, instructions with a destination register and a source register will have the leftmost register be the destination and the registers to the right be the source.


<lang ARM Assembly>MOV R0,R3 ;copy R3 to R0
<syntaxhighlight lang="arm assembly">MOV R0,R3 ;copy R3 to R0
ADD R2,R1,R5 ;add R1 to R5 and store the result in R2.</lang>
ADD R2,R1,R5 ;add R1 to R5 and store the result in R2.</syntaxhighlight>


However there is one exception: the <code>STR</code> command. Its source is on the left and its destination is on the right. This inverted syntax is not optional.
However there is one exception: the <code>STR</code> command. Its source is on the left and its destination is on the right. This inverted syntax is not optional.
<lang ARM Assembly>STR r0,[r4] ;store the contents of R0 into the memory location specified by R4.</lang>
<syntaxhighlight lang="arm assembly">STR r0,[r4] ;store the contents of R0 into the memory location specified by R4.</syntaxhighlight>


This was most likely done for symmetry with the "push/pop" commands:
This was most likely done for symmetry with the "push/pop" commands:
<lang ARM Assembly>STMFD sp!,{r0-r12,lr} ;push r0 thru r12 and the link register
<syntaxhighlight lang="arm assembly">STMFD sp!,{r0-r12,lr} ;push r0 thru r12 and the link register
LDMFD sp!,{r0-r12,pc} ;pop r0 thru r12, and the value that was in the link register is popped into the program counter.</lang>
LDMFD sp!,{r0-r12,pc} ;pop r0 thru r12, and the value that was in the link register is popped into the program counter.</syntaxhighlight>


=={{header|Arturo}}==
=={{header|Arturo}}==
In this case, we can define a reversed if-statement function (taking the block first, then the condition) and then "alias" a new symbol to it, as an infix operator (so that the block actually comes first, in terms of syntax:
In this case, we can define a reversed if-statement function (taking the block first, then the condition) and then "alias" a new symbol to it, as an infix operator (so that the block actually comes first, in terms of syntax:


<lang rebol>ifStatement: function [block, condition][
<syntaxhighlight lang="rebol">ifStatement: function [block, condition][
if condition -> do block
if condition -> do block
]
]
Line 127: Line 127:
variable: true
variable: true
[print "Variable is true!"] ?? variable
[print "Variable is true!"] ?? variable
]</lang>
]</syntaxhighlight>


{{out}}
{{out}}
Line 135: Line 135:
=={{header|Bracmat}}==
=={{header|Bracmat}}==
The match operator <code>:</code> can play the role of an inverted assignment operator <code>=</code>. The following two definitions of a function <code>double</code> are equivalent.
The match operator <code>:</code> can play the role of an inverted assignment operator <code>=</code>. The following two definitions of a function <code>double</code> are equivalent.
<lang bracmat>
<syntaxhighlight lang="bracmat">
double=.!arg+!arg;
double=.!arg+!arg;


(=.!arg+!arg):(=?double); { inverted assignment syntax, same result as above. }
(=.!arg+!arg):(=?double); { inverted assignment syntax, same result as above. }
</syntaxhighlight>
</lang>
Bracmat evaluates all left hand sides of all binary operators. How right hand sides are treated depends on the operator. The <code>=</code> operator does not evaluate its right hand side at all. The right hand side of the <code>:</code> operator is evaluated by a dedicated match evaluator, which for example sees the expression <code>?double</code> as a variable to be bound to some part of the left hand side of the <code>:</code> operator.
Bracmat evaluates all left hand sides of all binary operators. How right hand sides are treated depends on the operator. The <code>=</code> operator does not evaluate its right hand side at all. The right hand side of the <code>:</code> operator is evaluated by a dedicated match evaluator, which for example sees the expression <code>?double</code> as a variable to be bound to some part of the left hand side of the <code>:</code> operator.


The following two assignments are not equivalent:
The following two assignments are not equivalent:
<lang bracmat>foo=3+7 { assigns 3+7 to foo }
<syntaxhighlight lang="bracmat">foo=3+7 { assigns 3+7 to foo }
3+7:?foo { assigns 10 to foo }
3+7:?foo { assigns 10 to foo }
</syntaxhighlight>
</lang>


=={{header|C}}==
=={{header|C}}==
Line 153: Line 153:
The original would be "if (foo()) a = 4;" Here is the inverted if logic using "otherwise ... given () ;"
The original would be "if (foo()) a = 4;" Here is the inverted if logic using "otherwise ... given () ;"


<syntaxhighlight lang="c">
<lang c>
#include <stdio.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdlib.h>
Line 170: Line 170:
exit(0);
exit(0);
}
}
</syntaxhighlight>
</lang>


Which actually makes the main program look like:
Which actually makes the main program look like:


<syntaxhighlight lang="c">
<lang C>
main()
main()
{
{
Line 196: Line 196:
exit(0);
exit(0);
}
}
</syntaxhighlight>
</lang>


To make lint happy you need a /*FALLTHROUGH*/ before the case 0 (in the macro).
To make lint happy you need a /*FALLTHROUGH*/ before the case 0 (in the macro).
Line 202: Line 202:
=={{header|C++}}==
=={{header|C++}}==
Though rarely, if ever, used in practice, user-defined class types can have inverted syntax with assignment.
Though rarely, if ever, used in practice, user-defined class types can have inverted syntax with assignment.
<lang cpp>class invertedAssign {
<syntaxhighlight lang="cpp">class invertedAssign {
int data;
int data;
public:
public:
Line 223: Line 223:


std::cout << a.getData() << ' ' << b.getData() << '\n';
std::cout << a.getData() << ' ' << b.getData() << '\n';
}</lang>
}</syntaxhighlight>


It doesn't work if the left operand is not of the type <tt>invertedAssign</tt>.
It doesn't work if the left operand is not of the type <tt>invertedAssign</tt>.
Line 231: Line 231:
The "thread last" macro permits inversion of syntax in virtually all contexts. Any form for which the construction of a new list from consecutive elements doesn't change the semantics may be turned "inside-out"; this is to the exclusion of those containing function definitions and little else.
The "thread last" macro permits inversion of syntax in virtually all contexts. Any form for which the construction of a new list from consecutive elements doesn't change the semantics may be turned "inside-out"; this is to the exclusion of those containing function definitions and little else.


<lang Clojure>; normal
<syntaxhighlight lang="clojure">; normal
(if (= 1 1)
(if (= 1 1)
(print "Math works."))
(print "Math works."))
Line 242: Line 242:
(->> (print a " is " b)
(->> (print a " is " b)
(let [a 'homoiconicity
(let [a 'homoiconicity
b 'awesome]))</lang>
b 'awesome]))</syntaxhighlight>


Expanding the macro reveals the nature of the aforementioned limitation.
Expanding the macro reveals the nature of the aforementioned limitation.
<lang Clojure>((fn [x] (* x x) 5) ; Define a lambda and call it with 5.
<syntaxhighlight lang="clojure">((fn [x] (* x x) 5) ; Define a lambda and call it with 5.


(macroexpand-1 '(->> 5 (fn [x] (* x x))))
(macroexpand-1 '(->> 5 (fn [x] (* x x))))
(fn [x] (* x x) 5) ; Define a lambda that returns 5 regardless.</lang>
(fn [x] (* x x) 5) ; Define a lambda that returns 5 regardless.</syntaxhighlight>


The "thread first" macro (colloquially, the Thrush) provides a similar facility, wherein each expression becomes the first argument to the next.
The "thread first" macro (colloquially, the Thrush) provides a similar facility, wherein each expression becomes the first argument to the next.
<lang Clojure>(= (mod (inc 42) 7)
<syntaxhighlight lang="clojure">(= (mod (inc 42) 7)
(-> 42 inc (mod 7)))</lang>
(-> 42 inc (mod 7)))</syntaxhighlight>


=={{header|CoffeeScript}}==
=={{header|CoffeeScript}}==
CoffeeScript allows loop constructs and conditionals to be written in a suffix manner. Loop constructs evaluate to an array containing the result of each iteration; conditionals evaluates either the true-case expression or the false-case one.
CoffeeScript allows loop constructs and conditionals to be written in a suffix manner. Loop constructs evaluate to an array containing the result of each iteration; conditionals evaluates either the true-case expression or the false-case one.


<lang coffeescript>alert "hello" if true
<syntaxhighlight lang="coffeescript">alert "hello" if true
alert "hello again" unless false # the same as the above; unless is a negated if.
alert "hello again" unless false # the same as the above; unless is a negated if.


Line 264: Line 264:


idx = 0
idx = 0
arr = (++idx until idx is 10) # same as above; until is an inverted while.</lang>
arr = (++idx until idx is 10) # same as above; until is an inverted while.</syntaxhighlight>


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
Line 273: Line 273:




<lang lisp>(eval-when (:compile-toplevel :load-toplevel :execute)
<syntaxhighlight lang="lisp">(eval-when (:compile-toplevel :load-toplevel :execute)
(defun unrev-syntax (form)
(defun unrev-syntax (form)
(cond
(cond
Line 282: Line 282:


(defmacro rprogn (&body forms)
(defmacro rprogn (&body forms)
`(progn ,@(mapcar #'unrev-syntax forms)))</lang>
`(progn ,@(mapcar #'unrev-syntax forms)))</syntaxhighlight>


Interactive test run:
Interactive test run:
Line 303: Line 303:
(operator argument*) where argument* is the result of applying the unreversal to the argument:
(operator argument*) where argument* is the result of applying the unreversal to the argument:


<lang lisp>(eval-when (:compile-toplevel :load-toplevel :execute)
<syntaxhighlight lang="lisp">(eval-when (:compile-toplevel :load-toplevel :execute)
(defun unrev-syntax (form)
(defun unrev-syntax (form)
(cond
(cond
Line 316: Line 316:


(defmacro rprogn (&body forms)
(defmacro rprogn (&body forms)
`(progn ,@(mapcar #'unrev-syntax forms)))</lang>
`(progn ,@(mapcar #'unrev-syntax forms)))</syntaxhighlight>


<pre>[1]> (rprogn ((1 + 2) * (3 + 4)))
<pre>[1]> (rprogn ((1 + 2) * (3 + 4)))
Line 339: Line 339:
D enables a function to be called as if it were a method of its first argument. This feature often leads to natural syntax and readable, left-to-right expressions:
D enables a function to be called as if it were a method of its first argument. This feature often leads to natural syntax and readable, left-to-right expressions:


<lang d>#!/usr/bin/rdmd
<syntaxhighlight lang="d">#!/usr/bin/rdmd


import std.algorithm;
import std.algorithm;
Line 352: Line 352:


assert(r.equal([8, 16, 10, 14]));
assert(r.equal([8, 16, 10, 14]));
}</lang>
}</syntaxhighlight>


=={{header|EchoLisp}}==
=={{header|EchoLisp}}==
<lang scheme>
<syntaxhighlight lang="scheme">
;; use reader macros to transform (a OP b) into (OP b a)
;; use reader macros to transform (a OP b) into (OP b a)


Line 380: Line 380:
compiled :: (#when raining 'umbrella-need)
compiled :: (#when raining 'umbrella-need)


</syntaxhighlight>
</lang>


=={{header|Factor}}==
=={{header|Factor}}==
Since code is data in Factor, we can simply reverse it, transforming postfix into "prefix."
Since code is data in Factor, we can simply reverse it, transforming postfix into "prefix."
<lang Factor>1 1 + ! 2
<syntaxhighlight lang="factor">1 1 + ! 2
[ + 1 1 ] reverse call ! 2
[ + 1 1 ] reverse call ! 2
{ 1 2 3 4 5 } [ sq ] map ! { 1 4 9 16 25 }
{ 1 2 3 4 5 } [ sq ] map ! { 1 4 9 16 25 }
[ map [ sq ] { 1 2 3 4 5 } ] reverse call ! { 1 4 9 16 25 }</lang>
[ map [ sq ] { 1 2 3 4 5 } ] reverse call ! { 1 4 9 16 25 }</syntaxhighlight>


In fact, using a Lisp-style macro, we can perform this transformation at parse time:
In fact, using a Lisp-style macro, we can perform this transformation at parse time:


<lang factor>MACRO: pre ( quot -- quot ) reverse ;
<syntaxhighlight lang="factor">MACRO: pre ( quot -- quot ) reverse ;


[ + 2 2 ] pre ! 4</lang>
[ + 2 2 ] pre ! 4</syntaxhighlight>


Of course, this isn't true prefix because <code>+</code> retains its arity of <tt>2</tt>:
Of course, this isn't true prefix because <code>+</code> retains its arity of <tt>2</tt>:


<lang factor>[ + 3 + 2 2 ] pre ! 7</lang>
<syntaxhighlight lang="factor">[ + 3 + 2 2 ] pre ! 7</syntaxhighlight>


We can define a more accurate prefix macro for addition and subtraction in terms of <code>reduce</code>:
We can define a more accurate prefix macro for addition and subtraction in terms of <code>reduce</code>:


<lang factor>MACRO: pre ( quot -- quot ) 1 cut swap [ 0 ] dip reduce 1quotation ;
<syntaxhighlight lang="factor">MACRO: pre ( quot -- quot ) 1 cut swap [ 0 ] dip reduce 1quotation ;


[ + 1 2 3 4 5 ] pre ! 15</lang>
[ + 1 2 3 4 5 ] pre ! 15</syntaxhighlight>


Additionally, using parsing words, we can add any syntax we like. The <code>infix</code> vocabulary is an example of this:
Additionally, using parsing words, we can add any syntax we like. The <code>infix</code> vocabulary is an example of this:


<lang factor>USE: infix
<syntaxhighlight lang="factor">USE: infix
[infix
[infix
5*(1+1) ! 10
5*(1+1) ! 10
infix]</lang>
infix]</syntaxhighlight>


=={{header|Fortran}}==
=={{header|Fortran}}==
Leaving aside those who think that Fortran is inherently backward, assignment in Fortran is firmly right-to-left in the form <code>''variable'' = ''expression''</code> where the ''expression'' is computed in accordance with the precedence rules and the resulting value is assigned to the ''variable''.
Leaving aside those who think that Fortran is inherently backward, assignment in Fortran is firmly right-to-left in the form <code>''variable'' = ''expression''</code> where the ''expression'' is computed in accordance with the precedence rules and the resulting value is assigned to the ''variable''.


However, assignment-style constructions appear inside the INQUIRE statement as in <lang Fortran> INQUIRE(FILE = FILENAME(1:L), EXIST = MAYBE, ERR = 666, IOSTAT = RESULT) </lang>
However, assignment-style constructions appear inside the INQUIRE statement as in <syntaxhighlight lang="fortran"> INQUIRE(FILE = FILENAME(1:L), EXIST = MAYBE, ERR = 666, IOSTAT = RESULT) </syntaxhighlight>
Here, a logical variable MAYBE is to receive the value of whether or not the disc file named in FILENAME(1:L) exists, and integer variable RESULT contains an error code, zero if all went well - the file name may not be correctly formed, for example. Thus, FILE is receiving a value right-to-left on entry to the statement, while MAYBE and RESULT receive values left-to-right on exit from the statement. Despite appearances, <code>ERR = 666</code> is not an assignment statement; 666 is not an integer, it is a statement label to which execution will jump should an error arise. Similar arrangements apply for the file OPEN and CLOSE statements.
Here, a logical variable MAYBE is to receive the value of whether or not the disc file named in FILENAME(1:L) exists, and integer variable RESULT contains an error code, zero if all went well - the file name may not be correctly formed, for example. Thus, FILE is receiving a value right-to-left on entry to the statement, while MAYBE and RESULT receive values left-to-right on exit from the statement. Despite appearances, <code>ERR = 666</code> is not an assignment statement; 666 is not an integer, it is a statement label to which execution will jump should an error arise. Similar arrangements apply for the file OPEN and CLOSE statements.


Line 424: Line 424:
FreeBASIC has nothing like this built into the language.
FreeBASIC has nothing like this built into the language.
The nearest we can get is to define macros which reverse the order of the arguments:
The nearest we can get is to define macros which reverse the order of the arguments:
<lang freebasic>' FB 1.05.0 Win64
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64


#Define ThenIf(a, b) If b Then a
#Define ThenIf(a, b) If b Then a
Line 436: Line 436:
InvertAssign(a, b)
InvertAssign(a, b)
Print "b is"; b
Print "b is"; b
Sleep</lang>
Sleep</syntaxhighlight>


{{out}}
{{out}}
Line 456: Line 456:


Simulating inverted syntax with assignment is not possible.
Simulating inverted syntax with assignment is not possible.
<lang go>package main
<syntaxhighlight lang="go">package main


import "fmt"
import "fmt"
Line 485: Line 485:
needUmbrella = itrue.iif(raining)
needUmbrella = itrue.iif(raining)
fmt.Printf("Is it raining? %t. Do I need an umbrella? %t\n", raining, needUmbrella)
fmt.Printf("Is it raining? %t. Do I need an umbrella? %t\n", raining, needUmbrella)
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 498: Line 498:
However, for the common case where you want to perform a certain action only when some condition holds, you can define a simple binary operator:
However, for the common case where you want to perform a certain action only when some condition holds, you can define a simple binary operator:


<lang Haskell>when :: Monad m => m () -> Bool -> m ()
<syntaxhighlight lang="haskell">when :: Monad m => m () -> Bool -> m ()
action `when` condition = if condition then action else return ()
action `when` condition = if condition then action else return ()
</syntaxhighlight>
</lang>


Example usage:
Example usage:
Line 515: Line 515:
Haskell has a feature that can be considered "inverted" syntax (although it is not one of the types listed in the description of the task): The definition of local variables to be used in a function can be placed in a <code>where</code> clause that comes ''after'' the function body:
Haskell has a feature that can be considered "inverted" syntax (although it is not one of the types listed in the description of the task): The definition of local variables to be used in a function can be placed in a <code>where</code> clause that comes ''after'' the function body:


<lang haskell>func a b x = (x + y) / y
<syntaxhighlight lang="haskell">func a b x = (x + y) / y
where y = a * b</lang>
where y = a * b</syntaxhighlight>


This is in contrast to <code>let</code> expressions, where the definition of local variables comes before the scope that uses them:
This is in contrast to <code>let</code> expressions, where the definition of local variables comes before the scope that uses them:


<lang haskell>func a b x =
<syntaxhighlight lang="haskell">func a b x =
let y = a * b in
let y = a * b in
(x + y) / y</lang>
(x + y) / y</syntaxhighlight>


----
----
Line 530: Line 530:
'''bool x y p''' evaluates to '''x''' when '''p''' is '''False''', and evaluates to '''y''' when '''p''' is '''True'''.
'''bool x y p''' evaluates to '''x''' when '''p''' is '''False''', and evaluates to '''y''' when '''p''' is '''True'''.


<lang haskell>import Data.Bool (bool)
<syntaxhighlight lang="haskell">import Data.Bool (bool)


main :: IO ()
main :: IO ()
Line 545: Line 545:
<*> ["No need"]
<*> ["No need"]
<*> ["UMBRELLA !"]
<*> ["UMBRELLA !"]
<*> [raining, not raining]</lang>
<*> [raining, not raining]</syntaxhighlight>
{{Out}}
{{Out}}
<pre>No need
<pre>No need
Line 559: Line 559:
=={{header|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|Unicon}}==
Icon and Unicon can use [[Icon%2BUnicon/Intro#Conjunction.2C_yielding_a_different_result|expression conjunctions that select different sub-expression results]] to create this effect.
Icon and Unicon can use [[Icon%2BUnicon/Intro#Conjunction.2C_yielding_a_different_result|expression conjunctions that select different sub-expression results]] to create this effect.
<lang Icon>procedure main()
<syntaxhighlight lang="icon">procedure main()
raining := TRUE := 1 # there is no true/false null/non-null will do
raining := TRUE := 1 # there is no true/false null/non-null will do
if \raining then needumbrella := TRUE # normal
if \raining then needumbrella := TRUE # normal
needumbrella := 1(TRUE, \raining) # inverted (choose sub-expression 1)
needumbrella := 1(TRUE, \raining) # inverted (choose sub-expression 1)
end</lang>
end</syntaxhighlight>


=={{header|J}}==
=={{header|J}}==
Line 578: Line 578:
=={{header|jq}}==
=={{header|jq}}==
jq's syntax for associating a value with a variable is "inverted": the expression for associating a value, v, with a variable, $x, is:
jq's syntax for associating a value with a variable is "inverted": the expression for associating a value, v, with a variable, $x, is:
<lang jq>v as $x</lang>
<syntaxhighlight lang="jq">v as $x</syntaxhighlight>
Note, however, that there is limited support for the conventional "target = value" syntax in the context of JSON objects and arrays, but the semantics is purely functional. <br>
Note, however, that there is limited support for the conventional "target = value" syntax in the context of JSON objects and arrays, but the semantics is purely functional. <br>
For example, if o is {"a": 1}, then the expression:
For example, if o is {"a": 1}, then the expression:
<lang jq>o["a"] = 2
<syntaxhighlight lang="jq">o["a"] = 2
# or equivalently: o.a = 2</lang> emits another object equal to {"a": 2}.
# or equivalently: o.a = 2</syntaxhighlight> emits another object equal to {"a": 2}.


=={{header|Julia}}==
=={{header|Julia}}==
Line 589: Line 589:
Can be easily implemented as a macro:
Can be easily implemented as a macro:


<lang julia>macro inv(expr, cond)
<syntaxhighlight lang="julia">macro inv(expr, cond)
cond isa Expr && cond.head == :if || throw(ArgumentError("$cond is not an if expression"))
cond isa Expr && cond.head == :if || throw(ArgumentError("$cond is not an if expression"))
cond.args[2] = expr
cond.args[2] = expr
Line 595: Line 595:
end
end


@inv println("Wow! Lucky Guess!") if true else println("Not!") end</lang>
@inv println("Wow! Lucky Guess!") if true else println("Not!") end</syntaxhighlight>


=={{header|Kotlin}}==
=={{header|Kotlin}}==
Kotlin can get close to an inverted 'if' syntax by defining an infix function - 'iif' say. However, there doesn't appear to be a way to mimic inverted assignment.
Kotlin can get close to an inverted 'if' syntax by defining an infix function - 'iif' say. However, there doesn't appear to be a way to mimic inverted assignment.
<lang scala>// version 1.0.6
<syntaxhighlight lang="scala">// version 1.0.6


infix fun Boolean.iif(cond: Boolean) = if (cond) this else !this
infix fun Boolean.iif(cond: Boolean) = if (cond) this else !this
Line 607: Line 607:
val needUmbrella = true iif (raining)
val needUmbrella = true iif (raining)
println("Do I need an umbrella? ${if(needUmbrella) "Yes" else "No"}")
println("Do I need an umbrella? ${if(needUmbrella) "Yes" else "No"}")
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 618: Line 618:
Latitude, by default, does not support inverted conditionals, as its two primary means of conditional branching both involve the condition first.
Latitude, by default, does not support inverted conditionals, as its two primary means of conditional branching both involve the condition first.


<lang latitude>local 'raining = True.
<syntaxhighlight lang="latitude">local 'raining = True.
local 'needUmbrella = False.
local 'needUmbrella = False.


Line 627: Line 627:
{ raining. } ifTrue {
{ raining. } ifTrue {
needUmbrella = True.
needUmbrella = True.
}.</lang>
}.</syntaxhighlight>


However, such constructs can easily be added to the language.
However, such constructs can easily be added to the language.


<lang latitude>#'Method when := {
<syntaxhighlight lang="latitude">#'Method when := {
localize.
localize.
if ($1) then {
if ($1) then {
Line 644: Line 644:
;; Example usage
;; Example usage
{ needUmbrella = True. } when (raining).
{ needUmbrella = True. } when (raining).
{ needUmbrella = True. } unless (raining not).</lang>
{ needUmbrella = True. } unless (raining not).</syntaxhighlight>


Likewise, inverted assignment syntax is not supported natively, but it can be approximated in-language, using a definition similar to that of the built-in <code>local=</code>.
Likewise, inverted assignment syntax is not supported natively, but it can be approximated in-language, using a definition similar to that of the built-in <code>local=</code>.


<lang latitude>global let= := { self slot ($2) = #'$1. }.
<syntaxhighlight lang="latitude">global let= := { self slot ($2) = #'$1. }.


local 'a = 6.
local 'a = 6.
Line 654: Line 654:


let 6 = 'b.
let 6 = 'b.
println: b. ;; 6</lang>
println: b. ;; 6</syntaxhighlight>


=={{header|Lua}}==
=={{header|Lua}}==
In general, Lua does not support any ''truly'' inverted syntax, though there are some metamethod techniques and taking advantage of syntactic sugar that perhaps at least give the ''illusion'' that syntax has been inverted. Here, calling a library method passing a table, versus the table itself calling as if its own method, equivalently:
In general, Lua does not support any ''truly'' inverted syntax, though there are some metamethod techniques and taking advantage of syntactic sugar that perhaps at least give the ''illusion'' that syntax has been inverted. Here, calling a library method passing a table, versus the table itself calling as if its own method, equivalently:
<lang lua>a = {1,3,5,4,2} -- a "plain" table
<syntaxhighlight lang="lua">a = {1,3,5,4,2} -- a "plain" table
table.sort(a) -- library method passing a as param
table.sort(a) -- library method passing a as param
print(table.concat(a)) -- and again --> "12345"
print(table.concat(a)) -- and again --> "12345"
Line 665: Line 665:
setmetatable(b, {__index=table}) -- ..but now "meta-decorated"
setmetatable(b, {__index=table}) -- ..but now "meta-decorated"
b:sort() -- syntax sugar passes b as "self"
b:sort() -- syntax sugar passes b as "self"
print(b:concat()) -- and again --> "12345"</lang>
print(b:concat()) -- and again --> "12345"</syntaxhighlight>


=={{header|M2000 Interpreter}}==
=={{header|M2000 Interpreter}}==
Line 671: Line 671:
The third one is more complicated. We make a callback function which act as code of a module, with same scope, and use a module to check condition before we call the callback function
The third one is more complicated. We make a callback function which act as code of a module, with same scope, and use a module to check condition before we call the callback function


<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
expr=lambda ->{
expr=lambda ->{
Print "ok"
Print "ok"
Line 726: Line 726:
ExecCond Lazy$(&aa()), A=1
ExecCond Lazy$(&aa()), A=1
Print x=2
Print x=2
</syntaxhighlight>
</lang>


=={{header|m4}}==
=={{header|m4}}==
Line 732: Line 732:
to invert the arguments to the builtin macro, <code>ifelse</code>.
to invert the arguments to the builtin macro, <code>ifelse</code>.


<lang m4>define(`thenif', `ifelse($2, $3, `$1')')dnl
<syntaxhighlight lang="m4">define(`thenif', `ifelse($2, $3, `$1')')dnl
dnl
dnl
ifelse(eval(23 > 5), 1, 23 is greater than 5)
ifelse(eval(23 > 5), 1, 23 is greater than 5)
ifelse(eval(23 > 5), 0, math is broken)
ifelse(eval(23 > 5), 0, math is broken)
thenif(23 is greater than 5, eval(23 > 5), 1)
thenif(23 is greater than 5, eval(23 > 5), 1)
thenif(math is broken, eval(23 > 5), 0)</lang>
thenif(math is broken, eval(23 > 5), 0)</syntaxhighlight>


This example outputs these four lines.
This example outputs these four lines.
Line 749: Line 749:
=={{header|Mathematica}}/{{header|Wolfram Language}}==
=={{header|Mathematica}}/{{header|Wolfram Language}}==
Traditional form:
Traditional form:
<syntaxhighlight lang="mathematica">a = 4
<lang Mathematica>a = 4
->4
->4


Line 758: Line 758:
Print["This was expected"]
Print["This was expected"]
]
]
->This was expected</lang>
->This was expected</syntaxhighlight>


Inversion of syntax:
Inversion of syntax:
Line 788: Line 788:
These two clauses are exactly the same:
These two clauses are exactly the same:


<lang Mercury>:- pred progress(int::in, int::in, int::out, int::out) is det.
<syntaxhighlight lang="mercury">:- pred progress(int::in, int::in, int::out, int::out) is det.
progress(Past, Future, At, Total) :-
progress(Past, Future, At, Total) :-
At = Past + 1,
At = Past + 1,
Line 795: Line 795:
progress(Past, Future, At, Total) :-
progress(Past, Future, At, Total) :-
Past + Future = Total,
Past + Future = Total,
Past + 1 = At.</lang>
Past + 1 = At.</syntaxhighlight>


Order doesn't matter even when a data dependency tells you (and Mercury's compiler) what the order of evaluation must be:
Order doesn't matter even when a data dependency tells you (and Mercury's compiler) what the order of evaluation must be:


<lang Mercury>:- func example(int) = string.
<syntaxhighlight lang="mercury">:- func example(int) = string.
example(N) = S :-
example(N) = S :-
from_int(N) = S0,
from_int(N) = S0,
Line 806: Line 806:
example(N) = S :-
example(N) = S :-
pad_left(S0, '0', 3, S),
pad_left(S0, '0', 3, S),
from_int(N) = S0.</lang>
from_int(N) = S0.</syntaxhighlight>


Data dependencies are most obvious when state is threaded through a clause:
Data dependencies are most obvious when state is threaded through a clause:


<lang Mercury>main(IO0, IO) :-
<syntaxhighlight lang="mercury">main(IO0, IO) :-
io.write_string("Hello, ", IO0, IO1),
io.write_string("Hello, ", IO0, IO1),
io.write_string("world!\n", IO1, IO).
io.write_string("world!\n", IO1, IO).
Line 816: Line 816:
main(!IO) :-
main(!IO) :-
io.write_string("Hello, ", !IO),
io.write_string("Hello, ", !IO),
io.write_string("world!\n", !IO).</lang>
io.write_string("world!\n", !IO).</syntaxhighlight>


The io.write_string/2's in the first example could be written in either order and the result would be the same, as the "world!\n" can't be written until the "Hello, " provides the IO1.
The io.write_string/2's in the first example could be written in either order and the result would be the same, as the "world!\n" can't be written until the "Hello, " provides the IO1.
Line 822: Line 822:
The order is still enforced by a data dependency, so
The order is still enforced by a data dependency, so


<lang Mercury>main(!IO) :-
<syntaxhighlight lang="mercury">main(!IO) :-
io.write_string(X, !IO), io.nl(!IO),
io.write_string(X, !IO), io.nl(!IO),
some_long_uninteresting_thing(X).
some_long_uninteresting_thing(X).
Line 834: Line 834:
main(!IO) :-
main(!IO) :-
io.nl(!IO), io.write_string(X, !IO),
io.nl(!IO), io.write_string(X, !IO),
some_long_uninteresting_thing(X).</lang>
some_long_uninteresting_thing(X).</syntaxhighlight>


=={{header|Metafont}}==
=={{header|Metafont}}==
Although there is an assignment operator, you can also define values of variables by equations, such as:
Although there is an assignment operator, you can also define values of variables by equations, such as:
<lang metafont>x=6;
<syntaxhighlight lang="metafont">x=6;
7=y;</lang>
7=y;</syntaxhighlight>
Therefore it can be done both ways.
Therefore it can be done both ways.


Line 846: Line 846:
Inverted syntax in Nim can be achieved through the use of templates as operators:
Inverted syntax in Nim can be achieved through the use of templates as operators:


<lang nim>#--
<syntaxhighlight lang="nim">#--
# if statements
# if statements
#--
#--
Line 876: Line 876:


# Inverted syntax
# Inverted syntax
6 ~= a</lang>
6 ~= a</syntaxhighlight>


=={{header|Oforth}}==
=={{header|Oforth}}==
Line 887: Line 887:
=={{header|OxygenBasic}}==
=={{header|OxygenBasic}}==
Macros may have localised scope, so they can be safely deployed as HumptyDumpty words.
Macros may have localised scope, so they can be safely deployed as HumptyDumpty words.
<lang oxygenbasic>
<syntaxhighlight lang="oxygenbasic">
macro cond(a,c) {c then a}
macro cond(a,c) {c then a}


Line 905: Line 905:


cond store(5,a), if c>4
cond store(5,a), if c>4
</syntaxhighlight>
</lang>


=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
{{works with|PARI/GP|version 2.4.2 and above}}
{{works with|PARI/GP|version 2.4.2 and above}}
GP does not include a syntax-inverted if, but that can be defined using closures.
GP does not include a syntax-inverted if, but that can be defined using closures.
<lang parigp>fi(f, condition)=if(condition,f());
<syntaxhighlight lang="parigp">fi(f, condition)=if(condition,f());


if(raining, print("Umbrella needed"))
if(raining, print("Umbrella needed"))
fi(->print("Umbrella needed"), raining)</lang>
fi(->print("Umbrella needed"), raining)</syntaxhighlight>


PARI can also be used to implement it more directly in GP.
PARI can also be used to implement it more directly in GP.
Line 920: Line 920:


Perl already has that:
Perl already has that:
<lang perl>if ($guess == 6) { print "Wow! Lucky Guess!"; }; # Traditional syntax
<syntaxhighlight lang="perl">if ($guess == 6) { print "Wow! Lucky Guess!"; }; # Traditional syntax
print 'Wow! Lucky Guess!' if $guess == 6; # Inverted syntax (note missing braces and parens)
print 'Wow! Lucky Guess!' if $guess == 6; # Inverted syntax (note missing braces and parens)
unless ($guess == 6) { print "Sorry, your guess was wrong!"; } # Traditional syntax
unless ($guess == 6) { print "Sorry, your guess was wrong!"; } # Traditional syntax
print 'Huh! You Guessed Wrong!' unless $guess == 6; # Inverted syntax</lang>
print 'Huh! You Guessed Wrong!' unless $guess == 6; # Inverted syntax</syntaxhighlight>


Inverted syntax can also be used with the ternary operator.
Inverted syntax can also be used with the ternary operator.
However this may produce different results to the traditional syntax form because when inverted syntax is used, we are effectively making an assignment to a ternary expression. so in the following example code, instead of the assignment being made to variable a (as it is in the traditional syntax form), the inverted syntax form will cause assignment to be made to either b or c, depending on value of the ok variable:
However this may produce different results to the traditional syntax form because when inverted syntax is used, we are effectively making an assignment to a ternary expression. so in the following example code, instead of the assignment being made to variable a (as it is in the traditional syntax form), the inverted syntax form will cause assignment to be made to either b or c, depending on value of the ok variable:


<lang perl># Note that the results obtained by the inverted syntax form
<syntaxhighlight lang="perl"># Note that the results obtained by the inverted syntax form
# may produce differing results from the traditional syntax form
# may produce differing results from the traditional syntax form
$a = $ok ? $b : $c; # Traditional syntax
$a = $ok ? $b : $c; # Traditional syntax
($ok ? $b : $c) = $a; # Inverted syntax</lang>
($ok ? $b : $c) = $a; # Inverted syntax</syntaxhighlight>


We can also emulate inverted syntax for scalar assignment by creating a function as follows:
We can also emulate inverted syntax for scalar assignment by creating a function as follows:


<lang perl>sub assign { $_[1] = $_[0] }
<syntaxhighlight lang="perl">sub assign { $_[1] = $_[0] }
$a = $b; # Traditional syntax
$a = $b; # Traditional syntax
assign $b, $a; # Inverted syntax</lang>
assign $b, $a; # Inverted syntax</syntaxhighlight>


Inverted list assignment is not possible because it prevents arrays from flattening.
Inverted list assignment is not possible because it prevents arrays from flattening.
Line 943: Line 943:
=={{header|Phix}}==
=={{header|Phix}}==
original... the got still you've as long as ,itself compile/run to used be can This
original... the got still you've as long as ,itself compile/run to used be can This
<!--<lang Phix>(notonline)-->
<!--<syntaxhighlight lang="phix">(notonline)-->
<span style="color: #008080;">if</span> <span style="color: #008080;">end</span>
<span style="color: #008080;">if</span> <span style="color: #008080;">end</span>
<span style="color: #0000FF;">(&</span><span style="color: #008000;">"test.exw"</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span><span style="color: #000000;">cl</span><span style="color: #0000FF;">)</span><span style="color: #7060A8;">system</span>
<span style="color: #0000FF;">(&</span><span style="color: #008000;">"test.exw"</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span><span style="color: #000000;">cl</span><span style="color: #0000FF;">)</span><span style="color: #7060A8;">system</span>
Line 962: Line 962:
<span style="color: #008080;">js without</span>
<span style="color: #008080;">js without</span>
<span style="color: #000000;">demo</span><span style="color: #0000FF;">\</span><span style="color: #000000;">rosetta</span><span style="color: #0000FF;">\</span><span style="color: #000000;">inverted_syntax</span><span style="color: #0000FF;">.</span><span style="color: #000000;">exw</span> <span style="color: #000080;font-style:italic;">--</span>
<span style="color: #000000;">demo</span><span style="color: #0000FF;">\</span><span style="color: #000000;">rosetta</span><span style="color: #0000FF;">\</span><span style="color: #000000;">inverted_syntax</span><span style="color: #0000FF;">.</span><span style="color: #000000;">exw</span> <span style="color: #000080;font-style:italic;">--</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
I should note that "if length(cl)>2 then" gets away by the skin of its teeth and would break were it written "if length(cl) > 2 then".<br>
I should note that "if length(cl)>2 then" gets away by the skin of its teeth and would break were it written "if length(cl) > 2 then".<br>
... and here is the original, which can be used to first create and then re-run to compile/run the above, in fact destroying/restoring/recreating it in the latter process.
... and here is the original, which can be used to first create and then re-run to compile/run the above, in fact destroying/restoring/recreating it in the latter process.
<!--<lang Phix>(notonline)-->
<!--<syntaxhighlight lang="phix">(notonline)-->
<span style="color: #000080;font-style:italic;">-- demo\rosetta\inverted_syntax.exw</span>
<span style="color: #000080;font-style:italic;">-- demo\rosetta\inverted_syntax.exw</span>
<span style="color: #008080;">without</span> <span style="color: #008080;">js</span>
<span style="color: #008080;">without</span> <span style="color: #008080;">js</span>
Line 984: Line 984:
<span style="color: #7060A8;">system</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cl</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]&</span><span style="color: #008000;">"test.exw"</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">system</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cl</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]&</span><span style="color: #008000;">"test.exw"</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<!--</lang>-->
<!--</syntaxhighlight>-->


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
We define a read macro for reverted syntax
We define a read macro for reverted syntax
<lang PicoLisp>(de rv Prg
<syntaxhighlight lang="picolisp">(de rv Prg
(append (last Prg) (head -1 Prg)) )</lang>
(append (last Prg) (head -1 Prg)) )</syntaxhighlight>
Test:
Test:
<pre>(de needUmbrella (Raining)
<pre>(de needUmbrella (Raining)
Line 1,017: Line 1,017:
=={{header|PowerShell}}==
=={{header|PowerShell}}==
The PowerShell syntax for an 'if' statement is very normal:
The PowerShell syntax for an 'if' statement is very normal:
<syntaxhighlight lang="powershell">
<lang PowerShell>
if ((Get-Date 5/27/2016).DayOfWeek -eq "Friday") {"Thank God it's Friday!"}
if ((Get-Date 5/27/2016).DayOfWeek -eq "Friday") {"Thank God it's Friday!"}
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>
<pre>
Line 1,025: Line 1,025:
</pre>
</pre>
The order of the condition and expression can be easily reversed (with a slight change in syntax):
The order of the condition and expression can be easily reversed (with a slight change in syntax):
<syntaxhighlight lang="powershell">
<lang PowerShell>
function Action ([scriptblock]$Expression, [Alias("if")][bool]$Test)
function Action ([scriptblock]$Expression, [Alias("if")][bool]$Test)
{
{
Line 1,034: Line 1,034:


say {"Thank God it's Friday!"} -if (Get-Date 5/27/2016).DayOfWeek -eq "Friday"
say {"Thank God it's Friday!"} -if (Get-Date 5/27/2016).DayOfWeek -eq "Friday"
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>
<pre>
Line 1,045: Line 1,045:
The facts themselves are usually expressed using "functors" involving parentheses, with the constant in front of the parentheses naming some property which applies to one or more items inside. As a result, they sometimes kind of look like backwards "is" statements.
The facts themselves are usually expressed using "functors" involving parentheses, with the constant in front of the parentheses naming some property which applies to one or more items inside. As a result, they sometimes kind of look like backwards "is" statements.


<lang prolog>% Dracula is a vampire.
<syntaxhighlight lang="prolog">% Dracula is a vampire.
% Also, you become a vampire if someone who is a vampire bites you.
% Also, you become a vampire if someone who is a vampire bites you.
vampire(dracula).
vampire(dracula).
Line 1,051: Line 1,051:


% Oh no! Dracula just bit Bob...
% Oh no! Dracula just bit Bob...
bites(dracula, bob).</lang>
bites(dracula, bob).</syntaxhighlight>


{{out}}
{{out}}
Line 1,064: Line 1,064:


=={{header|Python}}==
=={{header|Python}}==
<lang python>x = truevalue if condition else falsevalue</lang>
<syntaxhighlight lang="python">x = truevalue if condition else falsevalue</syntaxhighlight>


<lang python>with open("file.txt") as f:
<syntaxhighlight lang="python">with open("file.txt") as f:
something(f)</lang>
something(f)</syntaxhighlight>


=={{header|Qi}}==
=={{header|Qi}}==
<syntaxhighlight lang="qi">
<lang qi>
(define set-needumbrella
(define set-needumbrella
Raining -> (set needumbrella true) where (= true Raining)
Raining -> (set needumbrella true) where (= true Raining)
Line 1,098: Line 1,098:
(define set-needumbrella
(define set-needumbrella
A -> (set needumbrella A))
A -> (set needumbrella A))
</syntaxhighlight>
</lang>


=={{header|R}}==
=={{header|R}}==
Line 1,104: Line 1,104:
This can be done with a simple function.
This can be done with a simple function.


<lang R>do.if <- function(expr, cond) if(cond) expr</lang>
<syntaxhighlight lang="r">do.if <- function(expr, cond) if(cond) expr</syntaxhighlight>


Because R evaluates function arguments lazily, "expr" is never evaluated unless "cond" evaluates to true.
Because R evaluates function arguments lazily, "expr" is never evaluated unless "cond" evaluates to true.


<lang R>do.if(print("Wow! Lucky Guess!"), guess==6)</lang>
<syntaxhighlight lang="r">do.if(print("Wow! Lucky Guess!"), guess==6)</syntaxhighlight>


If you do not want to state "do.if" first, you can define an infix operator (any function whose name is bracketed in percent signs is treated as an infix operator), however custom infix operators have higher precedence than comparisons, so will usually require putting parentheses around the test.
If you do not want to state "do.if" first, you can define an infix operator (any function whose name is bracketed in percent signs is treated as an infix operator), however custom infix operators have higher precedence than comparisons, so will usually require putting parentheses around the test.


<lang r>`%if%` <- function(expr, cond) if(cond) expr
<syntaxhighlight lang="r">`%if%` <- function(expr, cond) if(cond) expr


print("Wow! Lucky Guess!") %if% (guess==6)</lang>
print("Wow! Lucky Guess!") %if% (guess==6)</syntaxhighlight>


=={{header|Racket}}==
=={{header|Racket}}==
Line 1,121: Line 1,121:
However, two <tt>.</tt>s allow infix notation in some cases.
However, two <tt>.</tt>s allow infix notation in some cases.


<lang racket>
<syntaxhighlight lang="racket">
#lang racket
#lang racket
(when #t (displayln "true"))
(when #t (displayln "true"))
Line 1,129: Line 1,129:
(set! a 5)
(set! a 5)
(a . set! . 6)
(a . set! . 6)
</syntaxhighlight>
</lang>


=={{header|Raku}}==
=={{header|Raku}}==
(formerly Perl 6)
(formerly Perl 6)
Like all Perls, Perl 6 has statement modifiers:
Like all Perls, Perl 6 has statement modifiers:
<lang perl6>if $guess == 6 { say "Wow! Lucky Guess!" } # Traditional
<syntaxhighlight lang="raku" line>if $guess == 6 { say "Wow! Lucky Guess!" } # Traditional
say 'Wow! Lucky Guess!' if $guess == 6; # Inverted
say 'Wow! Lucky Guess!' if $guess == 6; # Inverted
unless $guess == 6 { say "Huh! You Guessed Rong!" } # Traditional
unless $guess == 6 { say "Huh! You Guessed Rong!" } # Traditional
say 'Huh! You Guessed Rong!' unless $guess == 6; # Inverted</lang>
say 'Huh! You Guessed Rong!' unless $guess == 6; # Inverted</syntaxhighlight>


Perl also inverts the syntax of loops:
Perl also inverts the syntax of loops:
<lang perl6>while $i { --$i }
<syntaxhighlight lang="raku" line>while $i { --$i }
--$i while $i;
--$i while $i;


Line 1,147: Line 1,147:


for 1..10 { .say if $_ %% 2 }
for 1..10 { .say if $_ %% 2 }
.say if $_ %% 2 for 1..10; # list comprehension</lang>
.say if $_ %% 2 for 1..10; # list comprehension</syntaxhighlight>


Perl 6 has a system of metaoperators that modify the characteristics of normal operators. Among these is the <tt>R</tt> metaoperator, which is able to reverse the arguments of most infix operators (including user-defined ones).
Perl 6 has a system of metaoperators that modify the characteristics of normal operators. Among these is the <tt>R</tt> metaoperator, which is able to reverse the arguments of most infix operators (including user-defined ones).
So a reversed assignment is easy to write:
So a reversed assignment is easy to write:
<lang perl6>42 R= $_; say $_; # prints 42</lang>
<syntaxhighlight lang="raku" line>42 R= $_; say $_; # prints 42</syntaxhighlight>


Since, much like list operators, assignment loosens the precedence of the following expression to allow comma lists, reverse assignment of a list requires parens where the normal assignment would not:
Since, much like list operators, assignment loosens the precedence of the following expression to allow comma lists, reverse assignment of a list requires parens where the normal assignment would not:
<lang perl6>my @a = 1,2,3;
<syntaxhighlight lang="raku" line>my @a = 1,2,3;
(1,2,3) R= my @a;</lang>
(1,2,3) R= my @a;</syntaxhighlight>
However, generally in that case you'd use a feed operator anyway, which is like an object pipe, but unlike Unix pipes works in either direction:
However, generally in that case you'd use a feed operator anyway, which is like an object pipe, but unlike Unix pipes works in either direction:
<lang perl6>my @a <== 1,2,3;
<syntaxhighlight lang="raku" line>my @a <== 1,2,3;
1,2,3 ==> my @a;</lang>
1,2,3 ==> my @a;</syntaxhighlight>
We think this is much more readable than a reversed assignment.
We think this is much more readable than a reversed assignment.


One other interesting inversion is the ability to put the conditional of a repeat loop at either end, with identical test-after semantics:
One other interesting inversion is the ability to put the conditional of a repeat loop at either end, with identical test-after semantics:
<lang perl6>repeat {
<syntaxhighlight lang="raku" line>repeat {
$_ = prompt "Gimme a number: ";
$_ = prompt "Gimme a number: ";
} until /^\d+$/;
} until /^\d+$/;
Line 1,168: Line 1,168:
repeat until /^\d+$/ {
repeat until /^\d+$/ {
$_ = prompt "Gimme a number: ";
$_ = prompt "Gimme a number: ";
}</lang>
}</syntaxhighlight>
This might seem relatively useless, but it allows a variable to be declared in the conditional that isn't actually set until the loop body:
This might seem relatively useless, but it allows a variable to be declared in the conditional that isn't actually set until the loop body:
<lang perl6>repeat until my $answer ~~ 42 {
<syntaxhighlight lang="raku" line>repeat until my $answer ~~ 42 {
$answer = prompt "Gimme an answer: ";
$answer = prompt "Gimme an answer: ";
}</lang>
}</syntaxhighlight>
This would require a prior declaration (and two extra semicolons, horrors)
This would require a prior declaration (and two extra semicolons, horrors)
if written in the non-inverted form with the conditional at the bottom:
if written in the non-inverted form with the conditional at the bottom:
<lang perl6>my $answer;
<syntaxhighlight lang="raku" line>my $answer;
repeat {
repeat {
$answer = prompt "Gimme an answer: ";
$answer = prompt "Gimme an answer: ";
} until $answer ~~ 42;</lang>
} until $answer ~~ 42;</syntaxhighlight>
You can't just put the <tt>my</tt> on the <tt>$answer</tt> in the block because the conditional is outside the scope of the block, and would not see the declaration.
You can't just put the <tt>my</tt> on the <tt>$answer</tt> in the block because the conditional is outside the scope of the block, and would not see the declaration.


Line 1,187: Line 1,187:
SIGNAL {ON|OFF} someCondition {name}
SIGNAL {ON|OFF} someCondition {name}
</pre>
</pre>
<lang rexx>/*REXX program demonstrates a use of a special case of inverted syntax (via SIGNAL ON).*/
<syntaxhighlight lang="rexx">/*REXX program demonstrates a use of a special case of inverted syntax (via SIGNAL ON).*/
signal on syntax
signal on syntax
a=7
a=7
Line 1,196: Line 1,196:
say 'the REXX statement number is: ' sigL " and the REXX source is:"
say 'the REXX statement number is: ' sigL " and the REXX source is:"
say sourceLine(sigL)
say sourceLine(sigL)
exit 13</lang>
exit 13</syntaxhighlight>
'''output'''
'''output'''
<pre>
<pre>
Line 1,210: Line 1,210:
These always check the condition ''before'' running the statement.
These always check the condition ''before'' running the statement.


<lang ruby># Raise ArgumentError if n is negative.
<syntaxhighlight lang="ruby"># Raise ArgumentError if n is negative.
if n < 0 then raise ArgumentError, "negative n" end
if n < 0 then raise ArgumentError, "negative n" end
raise ArgumentError, "negative n" if n < 0
raise ArgumentError, "negative n" if n < 0
Line 1,224: Line 1,224:
# Another way to empty an array, printing each element.
# Another way to empty an array, printing each element.
until ary.empty? do puts ary.shift end
until ary.empty? do puts ary.shift end
puts ary.shift until ary.empty?</lang>
puts ary.shift until ary.empty?</syntaxhighlight>


One can also modify a compound statement, as in <code>(warn "cannot fork"; exit 1) unless Process.respond_to? :fork</code>.
One can also modify a compound statement, as in <code>(warn "cannot fork"; exit 1) unless Process.respond_to? :fork</code>.
Line 1,232: Line 1,232:


=={{header|Scala}}==
=={{header|Scala}}==
<lang scala>object Main extends App {
<syntaxhighlight lang="scala">object Main extends App {


val raining = true
val raining = true
val needUmbrella = raining
val needUmbrella = raining
println(s"Do I need an umbrella? ${if (needUmbrella) "Yes" else "No"}")
println(s"Do I need an umbrella? ${if (needUmbrella) "Yes" else "No"}")
}</lang>
}</syntaxhighlight>


=={{header|Sidef}}==
=={{header|Sidef}}==
<lang ruby># Inverted syntax with assignment
<syntaxhighlight lang="ruby"># Inverted syntax with assignment
var raining = true;
var raining = true;
[false]»(\var needumbrella);
[false]»(\var needumbrella);
Line 1,247: Line 1,247:
if (raining==true) {needumbrella=true};
if (raining==true) {needumbrella=true};
{needumbrella=true} -> if (raining==true);
{needumbrella=true} -> if (raining==true);
(needumbrella=true) if (raining==true);</lang>
(needumbrella=true) if (raining==true);</syntaxhighlight>


=={{header|Swift}}==
=={{header|Swift}}==
Inverted syntax can be done with custom operators
Inverted syntax can be done with custom operators
<lang Swift>infix operator ~= {}
<syntaxhighlight lang="swift">infix operator ~= {}
infix operator ! {}
infix operator ! {}


Line 1,279: Line 1,279:


// Inverted using a custom operator
// Inverted using a custom operator
_ = {stayInside = true} ! tornado</lang>
_ = {stayInside = true} ! tornado</syntaxhighlight>


=={{header|Tcl}}==
=={{header|Tcl}}==
Copied verbatim from do.tcl, a part of tcllib's control package.
Copied verbatim from do.tcl, a part of tcllib's control package.
<lang tcl>
<syntaxhighlight lang="tcl">
# do.tcl --
# do.tcl --
#
#
Line 1,368: Line 1,368:
package require control
package require control
control::do {set i 0; puts "hello world"; incr i} until {$i > 0}
control::do {set i 0; puts "hello world"; incr i} until {$i > 0}
</syntaxhighlight>
</lang>


A more radical and probably ill-advised approach is to use the above
A more radical and probably ill-advised approach is to use the above
and modify the default tcl unknown procedure along these lines:
and modify the default tcl unknown procedure along these lines:


<lang tcl>
<syntaxhighlight lang="tcl">
rename unknown __unknown
rename unknown __unknown
proc unknown {args} {
proc unknown {args} {
Line 1,386: Line 1,386:
% {set i 0; puts "hello world"; incr i} until {$i > 0}
% {set i 0; puts "hello world"; incr i} until {$i > 0}
hello world
hello world
</syntaxhighlight>
</lang>


=={{header|TI-83 BASIC}}==
=={{header|TI-83 BASIC}}==
Assignment uses inverted syntax.
Assignment uses inverted syntax.
<lang ti83b>536→N</lang>
<syntaxhighlight lang="ti83b">536→N</syntaxhighlight>


=={{header|Wortel}}==
=={{header|Wortel}}==
The <code>~</code> operator reverse the arguments of the next operator.
The <code>~</code> operator reverse the arguments of the next operator.
<lang wortel>; a = expr
<syntaxhighlight lang="wortel">; a = expr
:a expr
:a expr
; expr = a
; expr = a
Line 1,401: Line 1,401:
@if cond expr
@if cond expr
; if expr cond
; if expr cond
~@if expr cond</lang>
~@if expr cond</syntaxhighlight>


=={{header|Wren}}==
=={{header|Wren}}==
Line 1,407: Line 1,407:


Again, simulating inverted syntax with assignment is not possible.
Again, simulating inverted syntax with assignment is not possible.
<lang ecmascript>class IBool {
<syntaxhighlight lang="ecmascript">class IBool {
construct new(b) {
construct new(b) {
if (!(b is Bool)) Fiber.abort("B must be a boolean")
if (!(b is Bool)) Fiber.abort("B must be a boolean")
Line 1,428: Line 1,428:
raining = false
raining = false
needUmbrella = itrue.iff(raining)
needUmbrella = itrue.iff(raining)
System.print("Is it raining? %(raining). Do I need an umbrella? %(needUmbrella)")</lang>
System.print("Is it raining? %(raining). Do I need an umbrella? %(needUmbrella)")</syntaxhighlight>


{{out}}
{{out}}
Line 1,438: Line 1,438:
=={{header|Z80 Assembly}}==
=={{header|Z80 Assembly}}==
Syntax on the Z80 is very rigid; macros notwithstanding there is very little support for inverted syntax. However, since the CPU is little-endian, you can store 16-bit data as a word or 2 bytes:
Syntax on the Z80 is very rigid; macros notwithstanding there is very little support for inverted syntax. However, since the CPU is little-endian, you can store 16-bit data as a word or 2 bytes:
<lang z80>byte &EF,&BE
<syntaxhighlight lang="z80">byte &EF,&BE
word &BEEF</lang>
word &BEEF</syntaxhighlight>


Both of the above are equivalent.
Both of the above are equivalent.
Line 1,449: Line 1,449:
It is also useful to "unwind" computations so they are easier to read
It is also useful to "unwind" computations so they are easier to read
but not require any temp vars.
but not require any temp vars.
<lang zkl>if (raining==True) needumbrella:=True;
<syntaxhighlight lang="zkl">if (raining==True) needumbrella:=True;
(raining==True) : if (_) needumbrella:=True;</lang>
(raining==True) : if (_) needumbrella:=True;</syntaxhighlight>
<lang zkl>a := 6
<syntaxhighlight lang="zkl">a := 6
6 : a:=_</lang>
6 : a:=_</syntaxhighlight>
<lang zkl>key.sort(fcn(kv,kv2){kv[0] < kv2[0]}) : listUnzip(_) :
<syntaxhighlight lang="zkl">key.sort(fcn(kv,kv2){kv[0] < kv2[0]}) : listUnzip(_) :
D.SD((_).xplode()) : return(_);</lang>
D.SD((_).xplode()) : return(_);</syntaxhighlight>