Topic variable: Difference between revisions

m
→‎{{header|Wren}}: Changed to Wren S/H
m (→‎{{header|Perl 6}}: fix markup)
m (→‎{{header|Wren}}: Changed to Wren S/H)
 
(26 intermediate revisions by 16 users not shown)
Line 1:
{{task}}
Several programming languages offer syntax shortcuts to deal with the notion of "current" or "topic" variable. A topic variable is a [[Special variables|special variable]] with a very short name which can also often be omitted.
 
A topic variable is a [[Special variables|special variable]] with a very short name which can also often be omitted.
 
Demonstrate the utilization and behaviour of the topic variable within the language and explain or demonstrate how the topic variable behaves under different levels of nesting or scope, if this applies, within the language.
 
For instance you can (but you don't have to) show how the topic variable can be used by assigning the number <math>3</math> to it and then computing its square and square root.
<br><br>
 
=={{header|AppleScript}}==
Line 10 ⟶ 13:
AppleScript binds the name '''result''' to the value of the expression most recently evaluated in the current scope.
 
<langsyntaxhighlight lang="applescript">on run
1 + 2
Line 56 ⟶ 59:
end script
end if
end mReturn</langsyntaxhighlight>
{{Out}}
<pre>{9, 1.732050807569}</pre>
 
The name '''result''' is still bound in this way if the most recently evaluated expression is a script rather than a simple value:
<langsyntaxhighlight lang="applescript">on run
script
-- The given function applied to the value 3
Line 111 ⟶ 114:
end script
end if
end mReturn</langsyntaxhighlight>
{{Out}}
<pre>{9, 1.732050807569}</pre>
 
{{omit from|ARM Assembly}}
 
=={{header|Axe}}==
In Axe, evaluated expressions can be "remembered" until the next expression is evaluated.
<langsyntaxhighlight lang="axe">3
Disp *3▶Dec,i</langsyntaxhighlight>
 
Prints:
Line 126 ⟶ 131:
 
However, attempting to use the result now would result in garbage due to the ▶Dec and Disp commands overwriting the previous result.
 
=={{header|BASIC256}}==
<syntaxhighlight lang="freebasic">function Sum (x, y)
Sum = x + y # using name of function
end function
 
function SumR (x, y)
return x + y # using Return keyword which always returns immediately
end function
 
print Sum (1, 2)
print SumR(2, 3)</syntaxhighlight>
 
=={{header|Clojure}}==
The Clojure REPL has '''*1''' (and also '''*2''' and '''*3''' for the 2nd or 3rd most recent)
<langsyntaxhighlight lang="clojure">
user=> 3
3
Line 136 ⟶ 153:
user=> (Math/pow *2 0.5)
1.7320508075688772
</syntaxhighlight>
</lang>
 
=={{header|Erlang}}==
Line 151 ⟶ 168:
In a stack oriented language like Forth the definition of variables is minimized as much as possible. The closest thing to a topic variable is the use of '''R@'''. This gets the top item from the return stack, which by the way is also used for flow control. It is up to the programmer to keep the stack balanced. In some Forth dialects '''R@''' and '''I''' are identical. '''I''' is used as a loop index, e.g.
 
<langsyntaxhighlight lang="forth">: myloop 11 1 do i . loop cr ; myloop</langsyntaxhighlight>
 
Which will print all numbers from 1 to 10. A typical use of '''R@''' is illustrated here:
 
<langsyntaxhighlight lang="forth">: ^2 dup * ;
: sqrt 0 tuck ?do 1+ dup 2* 1+ +loop ;
: topic >r r@ ^2 . r@ sqrt . r> drop ;
 
23 topic</langsyntaxhighlight>
 
The word '''>R''' places the item on the return stack and the word '''R>''' retrieves it from the return stack - an experienced Forth programmer would optimize this definition even further. Note that for technical reasons all words listed cannot be used outside definitions, so it may be argued that Forth doesn't have topic variables.
Line 170 ⟶ 187:
Alternatively, the keyword 'Function' can itself be used as an implicitly defined variable and behaves in exactly the same way as the function's name when used in this role. Similarly, the keywords 'Property' or 'Operator' can be used to return values from properties or operators respectively.
 
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
' Three different ways of returning a value from a function
Line 189 ⟶ 206:
Print Sum2(2, 3)
Print Sum3(3, 4)
Sleep</langsyntaxhighlight>
 
{{out}}
Line 200 ⟶ 217:
=={{header|Go}}==
Go has nothing like this in the bare language, but the template package of the standard library has a similar mechanism. Templates can have named variables, but they also have a cursor, represented by a period '.' and called "dot", that refers to a current value.
<langsyntaxhighlight lang="go">package main
 
import (
Line 232 ⟶ 249:
`))
t.Execute(os.Stdout, "3")
}</langsyntaxhighlight>
{{out}}
<pre>
Line 242 ⟶ 259:
=={{header|Haskell}}==
In Haskell terminal GHCi or WinGHCi, topic variable is called: it.
<syntaxhighlight lang="haskell">
<lang Haskell>
Prelude> [1..10]
[1,2,3,4,5,6,7,8,9,10]
Prelude> map (^2) it
[1,4,9,16,25,36,49,64,81,100]
</syntaxhighlight>
</lang>
 
=={{header|J}}==
With this new definition of topic variables, the closest thing J has to a topic variable is probably dummy variables used in function definitions, because we always omit declaring which variables they are, and because we may omit them entirely. But, we still need to place the function in the context of the value it's being used on.
Line 253 ⟶ 271:
Thus, for example (entirely eliminating the variable representing the argument):
 
<langsyntaxhighlight Jlang="j"> example=: *:, %: NB. *: is square, %: is square root
example 3
9 1.73205</langsyntaxhighlight>
 
Or, if we want to see the dummy variable in place (though still not declared, because there is no point to that):
 
<langsyntaxhighlight Jlang="j"> Example=: verb def '(*: y), (%: y)'
Example 3
9 1.73205</langsyntaxhighlight>
 
Or course, if it's crucial to the concept of topic variables that they not be constrained to definitions of things like functions, then it might be argued that J does not have them.
Line 267 ⟶ 285:
On the third hand, note that "definitions of functions" do not actually need to be associated with names. At worst, some definitions might need to be enclosed in parenthesis:
 
<langsyntaxhighlight Jlang="j"> (*:, %:) 3
9 1.73205</langsyntaxhighlight>
 
And if we were to insist on leaving out functions, it's not clear that there would be much of anything left of the language to be doing anything with. See also Henry Rich's writeup on [http://www.jsoftware.com/docs/help701/jforc/tacit_programs.htm Tacit Programs].
 
=={{header|jq}}==
In jq, . (a period) generally refers to the "current input", which is always a JSON entity. For example, the jq program consisting of . alone is a filter, like "cat" in the Unix tradition.
 
The "." referring to the current input can often be omitted altogether, for example the expression ". | exp" for computing e<sup>x</sup> can always be written simply as "exp".
 
There are some special character combinations involving ".":
Line 285 ⟶ 303:
=={{header|Julia}}==
Julia REPL has `ans` variable:
<langsyntaxhighlight lang="julia">julia> 3
3
julia> ans * ans, ans - 1
(9, 2)</langsyntaxhighlight>
 
=={{header|Kotlin}}==
The closest thing Kotlin has to a topic variable is the identifier 'it' which implicitly refers to the parameter of a lambda expression when it only has one. As in the case of all other parameters in Kotlin, 'it' is read-only and is in scope until the end of the lambda expression.
<langsyntaxhighlight lang="scala">// version 1.1.2
 
fun main(args: Array<String>) {
Line 300 ⟶ 318:
println(Math.sqrt(it.toDouble()))
}
}</langsyntaxhighlight>
 
{{out}}
Line 309 ⟶ 327:
</pre>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
This depends on the Mathematica REPL. For the examples, I will use the textual format that Mathematica provides. Here's some basic examples:
<pre>In[1]:= 3
 
Out[1]= 3
 
In[2]:= %1^2
 
Out[2]= 9
 
In[3]:= Sqrt[%%]
 
Out[3]= Sqrt[3]
 
In[4]:= N[Out[-1]] (* for floating point *)
 
Out[4]= 1.73205</pre>
In this, I use 3 different forms. Here's a list of them:
Line 335 ⟶ 349:
When an input is reevaluated, it also reassigns all relative Ins and Outs. Look at this for an example of its strange effects:
<pre>In[1]:= In[2]
 
Out[1]= In[2]
 
In[2]:= In[1]
 
$IterationLimit::itlim: Iteration limit of 4096 exceeded.
 
Out[2]= Hold[In[1]]</pre>
In it, it gets stuck in an infinite loop between In[1] and In[2], which evaluate to each other.
 
=={{header|Nim}}==
 
In Nim, the special variable <code>_</code> may be considered as a topic variable. It is mainly used in loops when the value of the counter is not needed, for instance:
<syntaxhighlight lang="nim">for _ in 1..10:
echo "Hello World!"</syntaxhighlight>
 
Another kind of topic variable is <code>it</code> which is used in expressions in some templates. For instance:
<syntaxhighlight lang="nim">import sequtils
let x = [1, 2, 3, 4, 5]
let y = x.mapIt(it * it)
echo y # @[1, 4, 9, 16, 25]</syntaxhighlight>
 
=={{header|Oforth}}==
Line 349 ⟶ 372:
Oforth does not have global variables, topic or not.
 
The closest thing Oforth has to a topic variable definition is the top of its data stack which always holds the last result without the need to assign it to a (local) variable but I don't think it is the philosophy of this task.
 
This will push 3 on the stack and compute sq and sqrt :
<syntaxhighlight lang Oforth="oforth">3 dup sq swap sqrt</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
 
gp is a REPL for GP, within which <code>%</code> can be used to refer to the last result.
<langsyntaxhighlight lang="parigp">3
[sqrt(%),%^2]</langsyntaxhighlight>
{{out}}
<pre>%1 = 3
Line 364 ⟶ 387:
 
=={{header|Perl}}==
In Perl the topic variable is $_.
It is the default parameter for loops, and some functions e.g. 'sqrt':
 
<syntaxhighlight lang="perl">print sqrt . " " for (4, 16, 64)</syntaxhighlight>
In Perl the topic variable is $_. It is the default argument for many functions, including the square root. It is also the default parameter for loops:
{{out}}
 
<pre>2 4 8</pre>
<lang Perl>my $_ = 3;
print for $_**2, "\n", sqrt;</lang>
 
The topic parametervariable is lexical, so its use can be nested into several lexical scopes. However, assignment to the topic variable at loop declaration is not lexical, and a my function or local keyword is needed to enable the loops to nest:
However, assignment to the topic variable at loop declaration is not lexical,
and the 'local' keyword is needed to enable loops to nest.
 
<syntaxhighlight lang ="perl">for ($_ = 0; $_ <= 9; $_++1..2) {
print "Outerouter $_:\n";
printlocal "$_\n";
for (1..3) {
# The inner loop will not nest properly unless
print " inner $_,";
# it is preceded by a my statement
my $_; # This is required to nest the inner loop
for ($_ = 0; $_ <= 9; $_++) {
print "Inner";
print "$_\n";
}
print " fini\n";
# Alternatively we can use a local keyword in the
}</syntaxhighlight>
# inner loop declaration instead of a my statement
{{out}}
for (local $_ = 0; $_ <= 9; $_++) {
<pre>outer 1:
print "Alternative";
inner 1, inner 2, inner 3, fini
print "$_\n";
outer 2:
}
inner 1, inner 2, inner 3, fini</pre>
}</lang>
 
=={{header|Perl 6Phix}}==
The closest thing would be to declare a variable with just an underscore as its identifier.
 
<!--<syntaxhighlight lang="phix">(phixonline)-->
As in previous versions of Perl, in Perl6 the topic variable is $_. In addition to a direct affectation, it can also be set with the 'given' keyword. A method can be called from it with an implicit call:
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
 
<span style="color: #004080;">object</span> <span style="color: #000000;">_</span>
<lang perl6>given 3 {
<span style="color: #000000;">_</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">3</span>
.say for $_**2, .sqrt;
<span style="color: #0000FF;">?</span><span style="color: #000000;">_</span>
}</lang>
<span style="color: #0000FF;">?</span><span style="color: #000000;">_</span><span style="color: #0000FF;">*</span><span style="color: #000000;">_</span>
The scope of the <tt>$_</tt> variable is always lexical in Perl 6, though a function can access its caller's topic if it asks for it specially via <tt>CALLER::<$_></tt>.
<!--</syntaxhighlight>-->
{{out}}
<pre>
3
9
</pre>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">PicoLisp sets the value of the variable (symbol) '@' to the result of
conditional and controlling expressions in flow- and logic-functions (cond, if,
and, when, while, etc.).
Line 408 ⟶ 436:
 
For example, to read the current input channel until EOF, and print the square
of every item which is a number:</langsyntaxhighlight>
Test:
<langsyntaxhighlight PicoLisplang="picolisp">(while (read)
(when (num? @)
(println (* @ @)) ) )
Line 418 ⟶ 446:
xyz # Not a number
3 # Number
9 # -> print square</langsyntaxhighlight>
 
=={{header|PowerShell}}==
Line 427 ⟶ 455:
 
The most common use is in the <code>ForEach-Object</code> cmdlet:
<syntaxhighlight lang="powershell">
<lang PowerShell>
65..67 | ForEach-Object {$_ * 2} # Multiply the numbers by 2
65..67 | ForEach-Object {[char]$_ } # ASCII values of the numbers
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 441 ⟶ 469:
</pre>
Using <code>Where-Object</code> to filter the odd numbers from an array:
<syntaxhighlight lang="powershell">
<lang PowerShell>
65..67 | Where-Object {$_ % 2}
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 450 ⟶ 478:
</pre>
Using <code>Format-Wide</code> to force an array into columns:
<syntaxhighlight lang="powershell">
<lang PowerShell>
65..70 | Format-Wide {$_} -Column 3 -Force
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 461 ⟶ 489:
=={{header|Python}}==
Pythons REPL has '''_'''.
<langsyntaxhighlight lang="python">>>> 3
3
>>> _*_, _**0.5
(9, 1.7320508075688772)
>>> </langsyntaxhighlight>
 
=={{header|Racket}}==
Line 471 ⟶ 499:
Racket doesn't have a "built-in" concept of a topic variable, but one is easy to add to the language with some macros. In fact, the subject of adding such a facility to a language using a hygienic macro facility is a very popular topic in some macro circles, and Racket can do it very well using syntax parameters. In the following there is a demonstration of two implementation approaches, the first uses a "parameter" -- a runtime value that is bound to a value in some dynamic extent, and the second uses a "syntax parameter" which is something that refers indirectly to a plain binding, and this binding can be adjusted by macros to point at an existing "real" binding. See the end of the code for usage samples. (Note that there is no point to talk about how these things behave wrt scope: since Racket is flexible enough to implement these with very different scopes...)
 
<langsyntaxhighlight lang="racket">
#lang racket
 
Line 529 ⟶ 557:
)
(require 'sample2)
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
 
As in Perl, in Raku the topic variable is $_. In addition to a direct assigment, it can be set with the 'given' or 'with' keywords, or by some iteration operator ('for', 'map' etc). A method can be called from it with an implicit call:
 
<syntaxhighlight lang="raku" line>$_ = 'Outside';
for <3 5 7 10> {
print $_;
.³.map: { say join "\t", '', $_, .², .sqrt, .log(2), OUTER::<$_>, UNIT::<$_> }
}</syntaxhighlight>
{{Out}}
<pre>3 27 729 5.196152422706632 4.754887502163469 3 Outside
5 125 15625 11.180339887498949 6.965784284662088 5 Outside
7 343 117649 18.520259177452136 8.422064766172811 7 Outside
10 1000 1000000 31.622776601683793 9.965784284662087 10 Outside</pre>
Note: that the $_ inside the 'map' block is different than the $_ set in the 'for' block. The scope of the <tt>$_</tt> variable is always lexical in Raku, though a function can access topics in other scopes by specifying the scope: <code>CALLER::<$_></code> from within a subroutine, <code>OUTER::<$_></code> for the next enclosing block, <code>UNIT::<$_></code> for the outermost block in a compilation unit, etc. The scope modifiers may be stacked: <code>CALLER::OUTER::<$_></code> would be the topic variable of the next outer block of the current subroutines caller block.
 
The scope modifiers can only flow outward. There is no way to access the topic of a block enclosed within the current scope or in a separate scope 'branch'.
 
Also note: '''Any''' variable in other scopes can be accessed this way. This is just pointing out that the default (topic) variable also has this property.
 
=={{header|REXX}}==
With this new definition of topic variables, the closest thing REXX has to a topic variable is probably function/subroutine arguments being "passed" to the target function/subroutine/routine/procedure.
<langsyntaxhighlight lang="rexx">/*REXX pgmprogram shows something close to a "topic variable" (for funcsfunctions/subssubroutines).*/
parse arg N /*getobtain ana argvariable from CL,the maybe acmd 3?line. */
saycall mysub(squareIt N) ' ◄───' /*invoke a function to square it.da number*/
exit say result ' ◄───' /*stickdisplay areturned forkvalue infrom it, we'rethe donefunc.*/
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────MYSUB subroutine (function)─────────*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
mysub: return arg(1)**2 /*return the square of passed arg*/</lang>
squareIt: return arg(1) ** 2 /*return the square of passed argument.*/</syntaxhighlight>
'''output''' &nbsp; when the following input is used: &nbsp; <tt> 3 </tt>
{{out|output|text=&nbsp; when using the input of: &nbsp; &nbsp; <tt> 12 </tt>}}
<pre>
9144 ◄───
</pre>
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
see "sum1 = " + sum1(1,2) + nl
see "sum2 = " + sum2(2,3) + nl
Line 555 ⟶ 605:
func sum2 (x, y)
return x + y
</syntaxhighlight>
</lang>
Output:
<pre>
Line 565 ⟶ 615:
In Ruby the topic variable is $_ (same as Perl).
 
<langsyntaxhighlight lang="ruby">while DATA.gets # assigns to $_ (local scope)
print # If no arguments are given, prints $_
end
Line 571 ⟶ 621:
This is line one
This is line two
This is line three</langsyntaxhighlight>
 
{{out}}
Line 580 ⟶ 630:
</pre>
'''example:'''
<langsyntaxhighlight lang="ruby">DATA.gets
p [$_.to_i ** 2, Math.sqrt($_.to_i)] #=> [9, 1.7320508075688772]
__END__
3</langsyntaxhighlight>
The style of programming using $_ as an implicit parameter is gradually losing favor in the Ruby community.
 
=={{header|Scala}}==
<syntaxhighlight lang="scala">object TopicVar extends App {
class SuperString(val org: String){
def it(): Unit = println(org)
}
 
new SuperString("FvdB"){it()}
new SuperString("FvdB"){println(org)}
 
Seq(1).foreach {println}
Seq(2).foreach {println(_)}
Seq(4).foreach { it => println(it)}
Seq(8).foreach { it => println(it + it)}
}</syntaxhighlight>
 
=={{header|Sidef}}==
The underscore (''_'') topic variable is defined at compile-time in every block of a program. To call a method on it, we can just use the prefix dot (''.'') operator, followed by a method name, which is equivalent with ''_.method_name''
<langsyntaxhighlight lang="ruby">say [9,16,25].map {.sqrt}; # prints: [3, 4, 5]</langsyntaxhighlight>
 
=={{header|Standard ML}}==
The SML language itself does not define a topic variable, but interactive implementations may define their own.
For example the SML/NJ REPL defines a topic variable named <tt>it</tt> which is bound any time the user types an
expression in the REPL (as opposed to a declaration).
 
<langsyntaxhighlight lang="sml">- 3.0;
val it = 3.0 : real
- it * it;
Line 601 ⟶ 666:
- Math.sqrt it;
val it = 3.0 : real
-</langsyntaxhighlight>
 
=={{header|Tailspin}}==
The topic variable, or current value, is central to Tailspin and is represented as "the value without a name", simply "$".
The current value goes through a sequence of transformations and has the new transformed value at each stage of the chain.
To do more things with the same current value, a function/templates (here an inline function/templates) can be used to encapsulate several chains where the same current value is accessed at the start of each chain.
<syntaxhighlight lang="tailspin">
3 -> \($-1! $+1!\) -> $*$ -> [$-1..$+1] -> '$;
' -> !OUT::write
</syntaxhighlight>
{{out}}
<pre>
[3, 4, 5]
[15, 16, 17]
</pre>
 
=={{header|UNIX Shell}}==
Line 607 ⟶ 686:
The shell $? is a kind of limited topic variable that holds the return value of the last function called. However, using it in a function will change its value, so following the echo below, the dollarhook will now contain the return value of zero indicating a successful echo:
 
<langsyntaxhighlight lang="sh">multiply 3 4 # We assume this user defined function has been previously defined
echo $? # This will output 12, but $? will now be zero indicating a successful echo</langsyntaxhighlight>
 
=={{header|VBA}}==
VBA does not have special or topic variables. All variables have a letter as their first character.
 
=={{header|Wren}}==
Wren doesn't have topic variables as such though they can be simulated by declaring a variable with a short name (preferably a single capital letter) at the top of a module so that it is then in scope throughout the module. As Wren is dynamically typed, any value can be assigned to such a variable subsequently.
 
Note that you can't use a single or double underscore as the variable name for this purpose as they always denote instance or static fields of a class.
<syntaxhighlight lang="wren">var T // global scope
 
var doSomethingWithT = Fn.new { [T * T, T.sqrt] }
 
T = 3
System.print(doSomethingWithT.call())</syntaxhighlight>
 
{{out}}
<pre>
[9, 1.7320508075689]
</pre>
 
=={{header|zkl}}==
No topic variable pre se (a variable name can be a single character however), but underscore has a special meaning in some cases. Its use is scoped to the expression it is used in.
<langsyntaxhighlight lang="zkl">a,_,c:=List(1,2,3,4,5,6) //-->a=1, c=3, here _ is used as "ignore"
3.0 : _.sqrt() : println(_) //-->"1.73205", _ (and :) is used to "explode" a computation
// as syntactic sugar
1.0 + 2 : _.sqrt() : _.pow(4) // no variables used, the compiler "implodes" the computation
// --> 9
</syntaxhighlight>
</lang>
 
{{omit from|BASIC}}
{{omit from|C}}
{{omit from|C++}}
{{omit from|D}}
{{omit from|Delphi}}
{{omit from|Free Pascal}}
{{omit from|GUISS|Does not have any variables}}
{{omit from|Tcl|AgainstMicrosoft languageSmall philosophyBasic}}
{{omit from|OCaml}}
{{omit from|Pascal}}
{{omit from|Python|Against language philosophy of "Explicit is better than implicit"}}
{{omit from|Rust}}
{{omit from|Tcl|Against language philosophy}}
{{omit from|VBA}}
{{omit from|ZX Spectrum Basic}}
{{omit from|OCaml}}
[[Category:Basic language learning]]
9,479

edits