Inverted syntax: Difference between revisions

m
m (→‎{{header|Phix}}: added original)
 
(19 intermediate revisions by 10 users not shown)
Line 5:
In traditional syntax conditional expressions are usually shown before the action within a statement or code block:
 
<langsyntaxhighlight lang="pseudocode"> IF raining=true THEN needumbrella=true </langsyntaxhighlight>
 
In inverted syntax, the action is listed before the conditional expression in the statement or code block:
 
<langsyntaxhighlight lang="pseudocode"> needumbrella=true IF raining=true </langsyntaxhighlight>
 
'''Inverted syntax with assignment'''
Line 15:
In traditional syntax, assignments are usually expressed with the variable appearing before the expression:
 
<langsyntaxhighlight lang="pseudocode"> a = 6</langsyntaxhighlight>
 
In inverted syntax, the expression appears before the variable:
<langsyntaxhighlight lang="pseudocode"> 6 = a</langsyntaxhighlight>
 
'''Task'''
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.
<langsyntaxhighlight lang="6502asm">loop_MySubroutine:
; more than 127 bytes of code
 
dex
bne loop_MySubroutine ;assembler will display an error message that the branch is too far away.
; rest of program</langsyntaxhighlight>
 
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.
 
<langsyntaxhighlight lang="6502asm">loop_mySubroutine:
; more than 127 bytes of code
 
Line 46:
JMP loop_mySubroutine
continue:
; rest of program</langsyntaxhighlight>
 
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:
===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.
<langsyntaxhighlight lang="6502asm">word $BEEF
byte $EF,$BE</langsyntaxhighlight>
A hexdump of these bytes would display them the same, i.e.: <pre>EF BE EF BE</pre>
 
Line 60:
The only place where syntax is kind of inverted is <code>exit when</code> to exit loops:
 
<langsyntaxhighlight Adalang="ada">Foo := 1;
loop
exit when Foo = 10;
Foo := Foo + 1;
end loop;</langsyntaxhighlight>
 
=={{header|ALGOL 68}}==
{{works with|ALGOL 68G|Any - tested with release 2.8.win32}}
<langsyntaxhighlight lang="algol68"># Inverted assignment #
# 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 #
Line 96:
 
( 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 #</langsyntaxhighlight>
{{out}}
<pre>
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.
 
<langsyntaxhighlight ARMlang="arm Assemblyassembly">MOV R0,R3 ;copy R3 to R0
ADD R2,R1,R5 ;add R1 to R5 and store the result in R2.</langsyntaxhighlight>
 
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.
<langsyntaxhighlight ARMlang="arm Assemblyassembly">STR r0,[r4] ;store the contents of R0 into the memory location specified by R4.</langsyntaxhighlight>
 
This was most likely done for symmetry with the "push/pop" commands:
<langsyntaxhighlight ARMlang="arm Assemblyassembly">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.</langsyntaxhighlight>
 
=={{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:
 
<syntaxhighlight lang="rebol">ifStatement: function [block, condition][
if condition -> do block
]
alias.infix {??} 'ifStatement
 
do [
variable: true
[print "Variable is true!"] ?? variable
]</syntaxhighlight>
 
{{out}}
 
<pre>Variable is true!</pre>
 
=={{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.
<langsyntaxhighlight lang="bracmat">
double=.!arg+!arg;
 
(=.!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.
 
The following two assignments are not equivalent:
<langsyntaxhighlight lang="bracmat">foo=3+7 { assigns 3+7 to foo }
3+7:?foo { assigns 10 to foo }
</syntaxhighlight>
</lang>
 
=={{header|C}}==
Line 136 ⟶ 153:
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 <stdlib.h>
Line 153 ⟶ 170:
exit(0);
}
</syntaxhighlight>
</lang>
 
Which actually makes the main program look like:
 
<syntaxhighlight lang="c">
<lang C>
main()
{
Line 179 ⟶ 196:
exit(0);
}
</syntaxhighlight>
</lang>
 
To make lint happy you need a /*FALLTHROUGH*/ before the case 0 (in the macro).
Line 185 ⟶ 202:
=={{header|C++}}==
Though rarely, if ever, used in practice, user-defined class types can have inverted syntax with assignment.
<langsyntaxhighlight lang="cpp">class invertedAssign {
int data;
public:
Line 206 ⟶ 223:
 
std::cout << a.getData() << ' ' << b.getData() << '\n';
}</langsyntaxhighlight>
 
It doesn't work if the left operand is not of the type <tt>invertedAssign</tt>.
Line 214 ⟶ 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.
 
<langsyntaxhighlight Clojurelang="clojure">; normal
(if (= 1 1)
(print "Math works."))
Line 225 ⟶ 242:
(->> (print a " is " b)
(let [a 'homoiconicity
b 'awesome]))</langsyntaxhighlight>
 
Expanding the macro reveals the nature of the aforementioned limitation.
<langsyntaxhighlight Clojurelang="clojure">((fn [x] (* x x) 5) ; Define a lambda and call it with 5.
 
(macroexpand-1 '(->> 5 (fn [x] (* x x))))
(fn [x] (* x x) 5) ; Define a lambda that returns 5 regardless.</langsyntaxhighlight>
 
The "thread first" macro (colloquially, the Thrush) provides a similar facility, wherein each expression becomes the first argument to the next.
<langsyntaxhighlight Clojurelang="clojure">(= (mod (inc 42) 7)
(-> 42 inc (mod 7)))</langsyntaxhighlight>
 
=={{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.
 
<langsyntaxhighlight lang="coffeescript">alert "hello" if true
alert "hello again" unless false # the same as the above; unless is a negated if.
 
Line 247 ⟶ 264:
 
idx = 0
arr = (++idx until idx is 10) # same as above; until is an inverted while.</langsyntaxhighlight>
 
=={{header|Common Lisp}}==
Line 256 ⟶ 273:
 
 
<langsyntaxhighlight lang="lisp">(eval-when (:compile-toplevel :load-toplevel :execute)
(defun unrev-syntax (form)
(cond
Line 265 ⟶ 282:
 
(defmacro rprogn (&body forms)
`(progn ,@(mapcar #'unrev-syntax forms)))</langsyntaxhighlight>
 
Interactive test run:
Line 286 ⟶ 303:
(operator argument*) where argument* is the result of applying the unreversal to the argument:
 
<langsyntaxhighlight lang="lisp">(eval-when (:compile-toplevel :load-toplevel :execute)
(defun unrev-syntax (form)
(cond
Line 299 ⟶ 316:
 
(defmacro rprogn (&body forms)
`(progn ,@(mapcar #'unrev-syntax forms)))</langsyntaxhighlight>
 
<pre>[1]> (rprogn ((1 + 2) * (3 + 4)))
Line 322 ⟶ 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:
 
<langsyntaxhighlight lang="d">#!/usr/bin/rdmd
 
import std.algorithm;
Line 335 ⟶ 352:
 
assert(r.equal([8, 16, 10, 14]));
}</langsyntaxhighlight>
 
=={{header|EchoLisp}}==
<langsyntaxhighlight lang="scheme">
;; use reader macros to transform (a OP b) into (OP b a)
 
Line 363 ⟶ 380:
compiled :: (#when raining 'umbrella-need)
 
</syntaxhighlight>
</lang>
 
=={{header|Factor}}==
Since code is data in Factor, we can simply reverse it, transforming postfix into "prefix."
<langsyntaxhighlight Factorlang="factor">1 1 + ! 2
[ + 1 1 ] reverse call ! 2
{ 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 }</langsyntaxhighlight>
 
In fact, using a Lisp-style macro, we can perform this transformation at parse time:
 
<langsyntaxhighlight lang="factor">MACRO: pre ( quot -- quot ) reverse ;
 
[ + 2 2 ] pre ! 4</langsyntaxhighlight>
 
Of course, this isn't true prefix because <code>+</code> retains its arity of <tt>2</tt>:
 
<langsyntaxhighlight lang="factor">[ + 3 + 2 2 ] pre ! 7</langsyntaxhighlight>
 
We can define a more accurate prefix macro for addition and subtraction in terms of <code>reduce</code>:
 
<langsyntaxhighlight lang="factor">MACRO: pre ( quot -- quot ) 1 cut swap [ 0 ] dip reduce 1quotation ;
 
[ + 1 2 3 4 5 ] pre ! 15</langsyntaxhighlight>
 
Additionally, using parsing words, we can add any syntax we like. The <code>infix</code> vocabulary is an example of this:
 
<langsyntaxhighlight lang="factor">USE: infix
[infix
5*(1+1) ! 10
infix]</langsyntaxhighlight>
 
=={{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''.
 
However, assignment-style constructions appear inside the INQUIRE statement as in <langsyntaxhighlight Fortranlang="fortran"> INQUIRE(FILE = FILENAME(1:L), EXIST = MAYBE, ERR = 666, IOSTAT = RESULT) </langsyntaxhighlight>
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 407 ⟶ 424:
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:
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
#Define ThenIf(a, b) If b Then a
Line 419 ⟶ 436:
InvertAssign(a, b)
Print "b is"; b
Sleep</langsyntaxhighlight>
 
{{out}}
Line 429 ⟶ 446:
=={{header|Fōrmulæ}}==
 
{{FormulaeEntry|page=https://formulae.org/?script=examples/Inverted_syntax}}
Fōrmulæ programs are not textual, visualization/edition of programs is done showing/manipulating structures but not text. Moreover, there can be multiple visual representations of the same program. Even though it is possible to have textual representation &mdash;i.e. XML, JSON&mdash; they are intended for storage and transfer purposes more than visualization and edition.
 
'''Inverted syntax with conditional expressions'''
Programs in Fōrmulæ are created/edited online in its [https://formulae.org website], However they run on execution servers. By default remote servers are used, but they are limited in memory and processing power, since they are intended for demonstration and casual use. A local server can be downloaded and installed, it has no limitations (it runs in your own computer). Because of that, example programs can be fully visualized and edited, but some of them will not run if they require a moderate or heavy computation/memory resources, and no local server is being used.
 
The following is how is visualized the common IF expression:
In '''[https://formulae.org/?example=Inverted_syntax this]''' page you can see the program(s) related to this task and their results.
 
[[File:Fōrmulæ - Inverted syntax 01.png]]
 
The following is the visualization of the inverted IF expression. Notice that they are different expressions, in order that they can be visualized in different form, but they reduce the same way.
 
[[File:Fōrmulæ - Inverted syntax 02.png]]
 
'''Inverted syntax with assignment'''
 
The assignment expression does not have an inverted form.
 
=={{header|Go}}==
Line 439 ⟶ 466:
 
Simulating inverted syntax with assignment is not possible.
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 468 ⟶ 495:
needUmbrella = itrue.iif(raining)
fmt.Printf("Is it raining? %t. Do I need an umbrella? %t\n", raining, needUmbrella)
}</langsyntaxhighlight>
 
{{out}}
Line 481 ⟶ 508:
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:
 
<langsyntaxhighlight Haskelllang="haskell">when :: Monad m => m () -> Bool -> m ()
action `when` condition = if condition then action else return ()
</syntaxhighlight>
</lang>
 
Example usage:
Line 498 ⟶ 525:
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:
 
<langsyntaxhighlight lang="haskell">func a b x = (x + y) / y
where y = a * b</langsyntaxhighlight>
 
This is in contrast to <code>let</code> expressions, where the definition of local variables comes before the scope that uses them:
 
<langsyntaxhighlight lang="haskell">func a b x =
let y = a * b in
(x + y) / y</langsyntaxhighlight>
 
----
 
The standard ''Data.Bool'' module defines a ''bool'' function.
 
'''bool x y p''' evaluates to '''x''' when '''p''' is '''False''', and evaluates to '''y''' when '''p''' is '''True'''.
 
<syntaxhighlight lang="haskell">import Data.Bool (bool)
 
main :: IO ()
main = do
let raining = False
putStrLn $ bool "No need" "UMBRELLA !" raining
putStrLn $ flip bool "No need" "UMBRELLA !" raining
putStrLn "\n--------\n"
mapM_ putStrLn $
[bool, flip bool]
<*> ["No need"]
<*> ["UMBRELLA !"]
<*> [raining, not raining]</syntaxhighlight>
{{Out}}
<pre>No need
UMBRELLA !
 
--------
 
No need
UMBRELLA !
UMBRELLA !
No need</pre>
 
=={{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.
<langsyntaxhighlight Iconlang="icon">procedure main()
raining := TRUE := 1 # there is no true/false null/non-null will do
if \raining then needumbrella := TRUE # normal
needumbrella := 1(TRUE, \raining) # inverted (choose sub-expression 1)
end</langsyntaxhighlight>
 
=={{header|J}}==
Line 528 ⟶ 588:
=={{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:
<syntaxhighlight lang ="jq">v as $x</langsyntaxhighlight>
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:
<langsyntaxhighlight lang="jq">o["a"] = 2
# or equivalently: o.a = 2</langsyntaxhighlight> emits another object equal to {"a": 2}.
 
=={{header|Julia}}==
Line 539 ⟶ 599:
Can be easily implemented as a macro:
 
<langsyntaxhighlight lang="julia">macro inv(expr, cond)
cond isa Expr && cond.head == :if || throw(ArgumentError("$cond is not an if expression"))
cond.args[2] = expr
Line 545 ⟶ 605:
end
 
@inv println("Wow! Lucky Guess!") if true else println("Not!") end</langsyntaxhighlight>
 
=={{header|Koka}}==
Using the byref function and infix operators we can get both inverted assignments as well as inverted conditionals in Koka! However, the branch to the conditional is evaluated prior to the condition unless you explicitly delay it or accept a closure.
 
<syntaxhighlight lang="koka">
fun (=:)(c: c, v: local-var<h, c>): <local<h>> ()
v := c
 
fun (?)(c: c, b: bool): e maybe<c>
if b then Just(c) else Nothing
 
fun main()
var x := 4
6 =: std/core/types/byref(x)
x.println
val res = "Yes" ? True
match res
Just(a) -> println(a)
Nothing -> throw("Nothing")
</syntaxhighlight>
 
{{out}}
<pre>
6
Yes
</pre>
 
=={{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.
<langsyntaxhighlight lang="scala">// version 1.0.6
 
infix fun Boolean.iif(cond: Boolean) = if (cond) this else !this
Line 557 ⟶ 643:
val needUmbrella = true iif (raining)
println("Do I need an umbrella? ${if(needUmbrella) "Yes" else "No"}")
}</langsyntaxhighlight>
 
{{out}}
Line 568 ⟶ 654:
Latitude, by default, does not support inverted conditionals, as its two primary means of conditional branching both involve the condition first.
 
<langsyntaxhighlight lang="latitude">local 'raining = True.
local 'needUmbrella = False.
 
Line 577 ⟶ 663:
{ raining. } ifTrue {
needUmbrella = True.
}.</langsyntaxhighlight>
 
However, such constructs can easily be added to the language.
 
<langsyntaxhighlight lang="latitude">#'Method when := {
localize.
if ($1) then {
Line 594 ⟶ 680:
;; Example usage
{ needUmbrella = True. } when (raining).
{ needUmbrella = True. } unless (raining not).</langsyntaxhighlight>
 
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>.
 
<langsyntaxhighlight lang="latitude">global let= := { self slot ($2) = #'$1. }.
 
local 'a = 6.
Line 604 ⟶ 690:
 
let 6 = 'b.
println: b. ;; 6</langsyntaxhighlight>
 
=={{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:
<syntaxhighlight lang="lua">a = {1,3,5,4,2} -- a "plain" table
table.sort(a) -- library method passing a as param
print(table.concat(a)) -- and again --> "12345"
 
b = {1,3,5,4,2} -- a "plain" table, so far..
setmetatable(b, {__index=table}) -- ..but now "meta-decorated"
b:sort() -- syntax sugar passes b as "self"
print(b:concat()) -- and again --> "12345"</syntaxhighlight>
 
=={{header|M2000 Interpreter}}==
Line 610 ⟶ 707:
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 ->{
Print "ok"
Line 665 ⟶ 762:
ExecCond Lazy$(&aa()), A=1
Print x=2
</syntaxhighlight>
</lang>
 
=={{header|m4}}==
Line 671 ⟶ 768:
to invert the arguments to the builtin macro, <code>ifelse</code>.
 
<langsyntaxhighlight lang="m4">define(`thenif', `ifelse($2, $3, `$1')')dnl
dnl
ifelse(eval(23 > 5), 1, 23 is greater than 5)
ifelse(eval(23 > 5), 0, math is broken)
thenif(23 is greater than 5, eval(23 > 5), 1)
thenif(math is broken, eval(23 > 5), 0)</langsyntaxhighlight>
 
This example outputs these four lines.
Line 688 ⟶ 785:
=={{header|Mathematica}}/{{header|Wolfram Language}}==
Traditional form:
<syntaxhighlight lang="mathematica">a = 4
<lang Mathematica>a = 4
->4
 
Line 697 ⟶ 794:
Print["This was expected"]
]
->This was expected</langsyntaxhighlight>
 
Inversion of syntax:
Line 727 ⟶ 824:
These two clauses are exactly the same:
 
<langsyntaxhighlight Mercurylang="mercury">:- pred progress(int::in, int::in, int::out, int::out) is det.
progress(Past, Future, At, Total) :-
At = Past + 1,
Line 734 ⟶ 831:
progress(Past, Future, At, Total) :-
Past + Future = Total,
Past + 1 = At.</langsyntaxhighlight>
 
Order doesn't matter even when a data dependency tells you (and Mercury's compiler) what the order of evaluation must be:
 
<langsyntaxhighlight Mercurylang="mercury">:- func example(int) = string.
example(N) = S :-
from_int(N) = S0,
Line 745 ⟶ 842:
example(N) = S :-
pad_left(S0, '0', 3, S),
from_int(N) = S0.</langsyntaxhighlight>
 
Data dependencies are most obvious when state is threaded through a clause:
 
<langsyntaxhighlight Mercurylang="mercury">main(IO0, IO) :-
io.write_string("Hello, ", IO0, IO1),
io.write_string("world!\n", IO1, IO).
Line 755 ⟶ 852:
main(!IO) :-
io.write_string("Hello, ", !IO),
io.write_string("world!\n", !IO).</langsyntaxhighlight>
 
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 761 ⟶ 858:
The order is still enforced by a data dependency, so
 
<langsyntaxhighlight Mercurylang="mercury">main(!IO) :-
io.write_string(X, !IO), io.nl(!IO),
some_long_uninteresting_thing(X).
Line 773 ⟶ 870:
main(!IO) :-
io.nl(!IO), io.write_string(X, !IO),
some_long_uninteresting_thing(X).</langsyntaxhighlight>
 
=={{header|Metafont}}==
Although there is an assignment operator, you can also define values of variables by equations, such as:
<langsyntaxhighlight lang="metafont">x=6;
7=y;</langsyntaxhighlight>
Therefore it can be done both ways.
 
Line 785 ⟶ 882:
Inverted syntax in Nim can be achieved through the use of templates as operators:
 
<langsyntaxhighlight lang="nim">#--
# if statements
#--
Line 815 ⟶ 912:
 
# Inverted syntax
6 ~= a</langsyntaxhighlight>
 
=={{header|Oforth}}==
Line 826 ⟶ 923:
=={{header|OxygenBasic}}==
Macros may have localised scope, so they can be safely deployed as HumptyDumpty words.
<langsyntaxhighlight lang="oxygenbasic">
macro cond(a,c) {c then a}
 
Line 844 ⟶ 941:
 
cond store(5,a), if c>4
</syntaxhighlight>
</lang>
 
=={{header|PARI/GP}}==
{{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.
<langsyntaxhighlight lang="parigp">fi(f, condition)=if(condition,f());
 
if(raining, print("Umbrella needed"))
fi(->print("Umbrella needed"), raining)</langsyntaxhighlight>
 
PARI can also be used to implement it more directly in GP.
Line 859 ⟶ 956:
 
Perl already has that:
<langsyntaxhighlight 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)
unless ($guess == 6) { print "Sorry, your guess was wrong!"; } # Traditional syntax
print 'Huh! You Guessed Wrong!' unless $guess == 6; # Inverted syntax</langsyntaxhighlight>
 
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:
 
<langsyntaxhighlight lang="perl"># Note that the results obtained by the inverted syntax form
# may produce differing results from the traditional syntax form
$a = $ok ? $b : $c; # Traditional syntax
($ok ? $b : $c) = $a; # Inverted syntax</langsyntaxhighlight>
 
We can also emulate inverted syntax for scalar assignment by creating a function as follows:
 
<langsyntaxhighlight lang="perl">sub assign { $_[1] = $_[0] }
$a = $b; # Traditional syntax
assign $b, $a; # Inverted syntax</langsyntaxhighlight>
 
Inverted list assignment is not possible because it prevents arrays from flattening.
Line 882 ⟶ 979:
=={{header|Phix}}==
original... the got still you've as long as ,itself compile/run to used be can This
<!--<langsyntaxhighlight Phixlang="phix">(notonline)-->
<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>
Line 901 ⟶ 998:
<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>
<!--</langsyntaxhighlight>-->
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, albeitin fact destroying/restoring/recreating it in the latter process.
<!--<langsyntaxhighlight Phixlang="phix">(notonline)-->
<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>
Line 923 ⟶ 1,020:
<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>
<!--</langsyntaxhighlight>-->
 
=={{header|PicoLisp}}==
We define a read macro for reverted syntax
<langsyntaxhighlight PicoLisplang="picolisp">(de rv Prg
(append (last Prg) (head -1 Prg)) )</langsyntaxhighlight>
Test:
<pre>(de needUmbrella (Raining)
Line 956 ⟶ 1,053:
=={{header|PowerShell}}==
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!"}
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 964 ⟶ 1,061:
</pre>
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)
{
Line 973 ⟶ 1,070:
 
say {"Thank God it's Friday!"} -if (Get-Date 5/27/2016).DayOfWeek -eq "Friday"
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 984 ⟶ 1,081:
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.
 
<langsyntaxhighlight lang="prolog">% Dracula is a vampire.
% Also, you become a vampire if someone who is a vampire bites you.
vampire(dracula).
Line 990 ⟶ 1,087:
 
% Oh no! Dracula just bit Bob...
bites(dracula, bob).</langsyntaxhighlight>
 
{{out}}
Line 1,003 ⟶ 1,100:
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">x = truevalue if condition else falsevalue</langsyntaxhighlight>
 
<langsyntaxhighlight lang="python">with open("file.txt") as f:
something(f)</langsyntaxhighlight>
 
=={{header|Qi}}==
<syntaxhighlight lang="qi">
<lang qi>
(define set-needumbrella
Raining -> (set needumbrella true) where (= true Raining)
Line 1,037 ⟶ 1,134:
(define set-needumbrella
A -> (set needumbrella A))
</syntaxhighlight>
</lang>
 
=={{header|Quackery}}==
 
A Quackery program consists of numbers, words, and nests, collectively referred to as items. A nest is a sequence of zero or more items. Items are evaluated sequentially.
 
Some words can alter this sequential behaviour. <code>if</code> for example, causes the item following it to be skipped if the number on the top of data stack (henceforth just "the stack") is zero (i.e. false.)
 
So, given that the word <code>raining</code> returns a boolean (i.e. 0 or 1) indicating whether it is raining or not, and the word <code>use-umbrella</code> deploys an umbrella, the usual syntax would be <code>raining if use-umbrella</code>.
 
The word <code>'</code> alters the sequential flow by causing the item following it to be placed on the stack rather than being evaluated. The word <code>do</code> causes the item on the top of the stack to be evaluated. So we could define a new word, <code>if.1</code> with
 
<pre>[ swap do iff do else drop ] is if.1</pre>
 
which would allow us to use the syntax <code>' raining ' use-umbrella if.1</code>. (<code>iff</code> conditionally skips over two items, <code>else</code> unconditionally skips over one item.)
 
<code>'</code> is defined using the meta-control flow operator <code>]'[</code> thus: <code>[ ]'[ ] is '</code> Meta-control flow operators grant their behaviour to the word that calls them. So if we wanted the syntax <code>' use-umbrella if.2 raining</code> we could define <code>if.2</code> with
 
<pre>[ ]'[ do iff do else drop ] is if.2</pre>
 
Other syntaxes can be achieved by the judicious use of <code>'</code> and <code>]'[</code>. To demonstrate just one that avoids the use of <code>if ...</code> or <code>iff ... else ...</code> entirely, one could define a word <code>ifelse</code> as
 
<pre>[ not ]'[ nested ]'[ nested join swap peek do ] is ifelse</code></pre>
 
This would have the syntax <code>raining ifelse use-umbrella use-sunscreen</code> (for an appropriate definition of <code>use-sunscreen</code>.)
 
Quackery does not have variables, so there is not exact equivalent to assignment, but it does have ancillary stacks which can be used in a variable-like manner. <code>temp</code> is a predefined ancillary stack, and an item can be moved from the stack to it with the phrase <code>temp put</code>. As with the previous examples, <code>]'[</code> can be used to vary the syntax.
 
=={{header|R}}==
Line 1,043 ⟶ 1,166:
This can be done with a simple function.
 
<langsyntaxhighlight Rlang="r">do.if <- function(expr, cond) if(cond) expr</langsyntaxhighlight>
 
Because R evaluates function arguments lazily, "expr" is never evaluated unless "cond" evaluates to true.
 
<langsyntaxhighlight Rlang="r">do.if(print("Wow! Lucky Guess!"), guess==6)</langsyntaxhighlight>
 
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.
 
<langsyntaxhighlight lang="r">`%if%` <- function(expr, cond) if(cond) expr
 
print("Wow! Lucky Guess!") %if% (guess==6)</langsyntaxhighlight>
 
=={{header|Racket}}==
Line 1,060 ⟶ 1,183:
However, two <tt>.</tt>s allow infix notation in some cases.
 
<langsyntaxhighlight lang="racket">
#lang racket
(when #t (displayln "true"))
Line 1,068 ⟶ 1,191:
(set! a 5)
(a . set! . 6)
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
 
Like all Perls, Perl 6 has statement modifiers:
Raku 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
unless $guess == 6 { say "Huh! You Guessed Rong!" } # Traditional
say 'Huh! You Guessed Rong!' unless $guess == 6; # Inverted</langsyntaxhighlight>
 
PerlRaku can also invertsinvert the syntax of loops:
<syntaxhighlight lang="raku" perl6line>while $i { --$i }
--$i while $i;
 
Line 1,086 ⟶ 1,210:
 
for 1..10 { .say if $_ %% 2 }
.say if $_ %% 2 for 1..10; # list comprehension</langsyntaxhighlight>
 
Perl 6Raku 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:
<syntaxhighlight lang="raku" perl6line>42 R= $_; say $_; # prints 42</langsyntaxhighlight>
 
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:
<syntaxhighlight lang="raku" perl6line>my @a = 1,2,3;
(1,2,3) R= my @a;</langsyntaxhighlight>
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:
<syntaxhighlight lang="raku" perl6line>my @a <== 1,2,3;
1,2,3 ==> my @a;</langsyntaxhighlight>
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:
<syntaxhighlight lang="raku" perl6line>repeat {
$_ = prompt "Gimme a number: ";
} until /^\d+$/;
Line 1,107 ⟶ 1,231:
repeat until /^\d+$/ {
$_ = prompt "Gimme a number: ";
}</langsyntaxhighlight>
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:
<syntaxhighlight lang="raku" perl6line>repeat until my $answer ~~ 42 {
$answer = prompt "Gimme an answer: ";
}</langsyntaxhighlight>
This would require a prior declaration (and two extra semicolons, horrors)
if written in the non-inverted form with the conditional at the bottom:
<syntaxhighlight lang="raku" perl6line>my $answer;
repeat {
$answer = prompt "Gimme an answer: ";
} until $answer ~~ 42;</langsyntaxhighlight>
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,126 ⟶ 1,250:
SIGNAL {ON|OFF} someCondition {name}
</pre>
<langsyntaxhighlight lang="rexx">/*REXX program demonstrates a use of a special case of inverted syntax (via SIGNAL ON).*/
signal on syntax
a=7
Line 1,135 ⟶ 1,259:
say 'the REXX statement number is: ' sigL " and the REXX source is:"
say sourceLine(sigL)
exit 13</langsyntaxhighlight>
'''output'''
<pre>
Line 1,142 ⟶ 1,266:
zz=444 / (7-a)
</pre>
 
=={{header|RPL}}==
Assigning values to variables using <code>→</code> or <code>STO</code> commands presents an inverted syntax in RPL. It's also possible to invert syntax for conditional expressions, by pushing the action in the stack as a lambda expression before doing the test, but this isn't idiomatic.
≪ 1 → raining <span style="color:grey">@ Set raining to true</span>
≪ ≪ NEEDUMBRELLA ≫
'''IF''' raining '''THEN''' EVAL '''ELSE''' DROP '''END''' <span style="color:grey">@ Execute above action if true, else pop it from stack</span>
≫ ≫ '<span style="color:blue">TASK</span>' STO <span style="color:grey">@ Store above program in TASK variable</span>
 
=={{header|Ruby}}==
Line 1,149 ⟶ 1,280:
These always check the condition ''before'' running the statement.
 
<langsyntaxhighlight lang="ruby"># Raise ArgumentError if n is negative.
if n < 0 then raise ArgumentError, "negative n" end
raise ArgumentError, "negative n" if n < 0
Line 1,163 ⟶ 1,294:
# Another way to empty an array, printing each element.
until ary.empty? do puts ary.shift end
puts ary.shift until ary.empty?</langsyntaxhighlight>
 
One can also modify a compound statement, as in <code>(warn "cannot fork"; exit 1) unless Process.respond_to? :fork</code>.
Line 1,171 ⟶ 1,302:
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala">object Main extends App {
 
val raining = true
val needUmbrella = raining
println(s"Do I need an umbrella? ${if (needUmbrella) "Yes" else "No"}")
}</langsyntaxhighlight>
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby"># Inverted syntax with assignment
var raining = true;
[false]»(\var needumbrella);
Line 1,186 ⟶ 1,317:
if (raining==true) {needumbrella=true};
{needumbrella=true} -> if (raining==true);
(needumbrella=true) if (raining==true);</langsyntaxhighlight>
 
=={{header|Swift}}==
Inverted syntax can be done with custom operators
<langsyntaxhighlight Swiftlang="swift">infix operator ~= {}
infix operator ! {}
 
Line 1,218 ⟶ 1,349:
 
// Inverted using a custom operator
_ = {stayInside = true} ! tornado</langsyntaxhighlight>
 
=={{header|Tcl}}==
Copied verbatim from do.tcl, a part of tcllib's control package.
<langsyntaxhighlight lang="tcl">
# do.tcl --
#
Line 1,307 ⟶ 1,438:
package require control
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
and modify the default tcl unknown procedure along these lines:
 
<langsyntaxhighlight lang="tcl">
rename unknown __unknown
proc unknown {args} {
Line 1,325 ⟶ 1,456:
% {set i 0; puts "hello world"; incr i} until {$i > 0}
hello world
</syntaxhighlight>
</lang>
 
=={{header|TI-83 BASIC}}==
Assignment uses inverted syntax.
<syntaxhighlight lang ="ti83b">536→N</langsyntaxhighlight>
 
=={{header|Wortel}}==
The <code>~</code> operator reverse the arguments of the next operator.
<langsyntaxhighlight lang="wortel">; a = expr
:a expr
; expr = a
Line 1,340 ⟶ 1,471:
@if cond expr
; if expr cond
~@if expr cond</langsyntaxhighlight>
 
=={{header|Wren}}==
Line 1,346 ⟶ 1,477:
 
Again, simulating inverted syntax with assignment is not possible.
<langsyntaxhighlight ecmascriptlang="wren">class IBool {
construct new(b) {
if (!(b is Bool)) Fiber.abort("B must be a boolean")
Line 1,367 ⟶ 1,498:
raining = false
needUmbrella = itrue.iff(raining)
System.print("Is it raining? %(raining). Do I need an umbrella? %(needUmbrella)")</langsyntaxhighlight>
 
{{out}}
Line 1,377 ⟶ 1,508:
=={{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:
<langsyntaxhighlight lang="z80">byte &EF,&BE
word &BEEF</langsyntaxhighlight>
 
Both of the above are equivalent.
Line 1,388 ⟶ 1,519:
It is also useful to "unwind" computations so they are easier to read
but not require any temp vars.
<langsyntaxhighlight lang="zkl">if (raining==True) needumbrella:=True;
(raining==True) : if (_) needumbrella:=True;</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">a := 6
6 : a:=_</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">key.sort(fcn(kv,kv2){kv[0] < kv2[0]}) : listUnzip(_) :
D.SD((_).xplode()) : return(_);</langsyntaxhighlight>
 
 
2,120

edits