Topic variable: Difference between revisions

From Rosetta Code
Content added Content deleted
(add omit from Delphi, Free Pascal, and Pascal; alphabetize omit from list; remove trailing blanks [from non-sourcecode])
m (→‎{{header|Wren}}: Changed to Wren S/H)
 
(7 intermediate revisions by 7 users not shown)
Line 13: Line 13:
AppleScript binds the name '''result''' to the value of the expression most recently evaluated in the current scope.
AppleScript binds the name '''result''' to the value of the expression most recently evaluated in the current scope.


<lang applescript>on run
<syntaxhighlight lang="applescript">on run
1 + 2
1 + 2
Line 59: Line 59:
end script
end script
end if
end if
end mReturn</lang>
end mReturn</syntaxhighlight>
{{Out}}
{{Out}}
<pre>{9, 1.732050807569}</pre>
<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:
The name '''result''' is still bound in this way if the most recently evaluated expression is a script rather than a simple value:
<lang applescript>on run
<syntaxhighlight lang="applescript">on run
script
script
-- The given function applied to the value 3
-- The given function applied to the value 3
Line 114: Line 114:
end script
end script
end if
end if
end mReturn</lang>
end mReturn</syntaxhighlight>
{{Out}}
{{Out}}
<pre>{9, 1.732050807569}</pre>
<pre>{9, 1.732050807569}</pre>
Line 122: Line 122:
=={{header|Axe}}==
=={{header|Axe}}==
In Axe, evaluated expressions can be "remembered" until the next expression is evaluated.
In Axe, evaluated expressions can be "remembered" until the next expression is evaluated.
<lang axe>3
<syntaxhighlight lang="axe">3
Disp *3▶Dec,i</lang>
Disp *3▶Dec,i</syntaxhighlight>


Prints:
Prints:
Line 131: Line 131:


However, attempting to use the result now would result in garbage due to the ▶Dec and Disp commands overwriting the previous result.
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}}==
=={{header|Clojure}}==
The Clojure REPL has '''*1''' (and also '''*2''' and '''*3''' for the 2nd or 3rd most recent)
The Clojure REPL has '''*1''' (and also '''*2''' and '''*3''' for the 2nd or 3rd most recent)
<lang clojure>
<syntaxhighlight lang="clojure">
user=> 3
user=> 3
3
3
Line 141: Line 153:
user=> (Math/pow *2 0.5)
user=> (Math/pow *2 0.5)
1.7320508075688772
1.7320508075688772
</syntaxhighlight>
</lang>


=={{header|Erlang}}==
=={{header|Erlang}}==
Line 156: Line 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.
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.


<lang forth>: myloop 11 1 do i . loop cr ; myloop</lang>
<syntaxhighlight lang="forth">: myloop 11 1 do i . loop cr ; myloop</syntaxhighlight>


Which will print all numbers from 1 to 10. A typical use of '''R@''' is illustrated here:
Which will print all numbers from 1 to 10. A typical use of '''R@''' is illustrated here:


<lang forth>: ^2 dup * ;
<syntaxhighlight lang="forth">: ^2 dup * ;
: sqrt 0 tuck ?do 1+ dup 2* 1+ +loop ;
: sqrt 0 tuck ?do 1+ dup 2* 1+ +loop ;
: topic >r r@ ^2 . r@ sqrt . r> drop ;
: topic >r r@ ^2 . r@ sqrt . r> drop ;


23 topic</lang>
23 topic</syntaxhighlight>


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.
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 175: Line 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.
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.


<lang freebasic>' FB 1.05.0 Win64
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64


' Three different ways of returning a value from a function
' Three different ways of returning a value from a function
Line 194: Line 206:
Print Sum2(2, 3)
Print Sum2(2, 3)
Print Sum3(3, 4)
Print Sum3(3, 4)
Sleep</lang>
Sleep</syntaxhighlight>


{{out}}
{{out}}
Line 205: Line 217:
=={{header|Go}}==
=={{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.
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.
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 237: Line 249:
`))
`))
t.Execute(os.Stdout, "3")
t.Execute(os.Stdout, "3")
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 247: Line 259:
=={{header|Haskell}}==
=={{header|Haskell}}==
In Haskell terminal GHCi or WinGHCi, topic variable is called: it.
In Haskell terminal GHCi or WinGHCi, topic variable is called: it.
<syntaxhighlight lang="haskell">
<lang Haskell>
Prelude> [1..10]
Prelude> [1..10]
[1,2,3,4,5,6,7,8,9,10]
[1,2,3,4,5,6,7,8,9,10]
Prelude> map (^2) it
Prelude> map (^2) it
[1,4,9,16,25,36,49,64,81,100]
[1,4,9,16,25,36,49,64,81,100]
</syntaxhighlight>
</lang>


=={{header|J}}==
=={{header|J}}==
Line 259: Line 271:
Thus, for example (entirely eliminating the variable representing the argument):
Thus, for example (entirely eliminating the variable representing the argument):


<lang J> example=: *:, %: NB. *: is square, %: is square root
<syntaxhighlight lang="j"> example=: *:, %: NB. *: is square, %: is square root
example 3
example 3
9 1.73205</lang>
9 1.73205</syntaxhighlight>


Or, if we want to see the dummy variable in place (though still not declared, because there is no point to that):
Or, if we want to see the dummy variable in place (though still not declared, because there is no point to that):


<lang J> Example=: verb def '(*: y), (%: y)'
<syntaxhighlight lang="j"> Example=: verb def '(*: y), (%: y)'
Example 3
Example 3
9 1.73205</lang>
9 1.73205</syntaxhighlight>


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.
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 273: Line 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:
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:


<lang J> (*:, %:) 3
<syntaxhighlight lang="j"> (*:, %:) 3
9 1.73205</lang>
9 1.73205</syntaxhighlight>


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].
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].
Line 291: Line 303:
=={{header|Julia}}==
=={{header|Julia}}==
Julia REPL has `ans` variable:
Julia REPL has `ans` variable:
<lang julia>julia> 3
<syntaxhighlight lang="julia">julia> 3
3
3
julia> ans * ans, ans - 1
julia> ans * ans, ans - 1
(9, 2)</lang>
(9, 2)</syntaxhighlight>


=={{header|Kotlin}}==
=={{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.
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.
<lang scala>// version 1.1.2
<syntaxhighlight lang="scala">// version 1.1.2


fun main(args: Array<String>) {
fun main(args: Array<String>) {
Line 306: Line 318:
println(Math.sqrt(it.toDouble()))
println(Math.sqrt(it.toDouble()))
}
}
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 315: Line 327:
</pre>
</pre>


=={{header|Mathematica}}==
=={{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:
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
<pre>In[1]:= 3

Out[1]= 3
Out[1]= 3


In[2]:= %1^2
In[2]:= %1^2

Out[2]= 9
Out[2]= 9


In[3]:= Sqrt[%%]
In[3]:= Sqrt[%%]

Out[3]= Sqrt[3]
Out[3]= Sqrt[3]


In[4]:= N[Out[-1]] (* for floating point *)
In[4]:= N[Out[-1]] (* for floating point *)

Out[4]= 1.73205</pre>
Out[4]= 1.73205</pre>
In this, I use 3 different forms. Here's a list of them:
In this, I use 3 different forms. Here's a list of them:
Line 341: Line 349:
When an input is reevaluated, it also reassigns all relative Ins and Outs. Look at this for an example of its strange effects:
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]
<pre>In[1]:= In[2]

Out[1]= In[2]
Out[1]= In[2]


In[2]:= In[1]
In[2]:= In[1]

$IterationLimit::itlim: Iteration limit of 4096 exceeded.
$IterationLimit::itlim: Iteration limit of 4096 exceeded.

Out[2]= Hold[In[1]]</pre>
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.
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}}==
=={{header|Oforth}}==
Line 358: Line 375:


This will push 3 on the stack and compute sq and sqrt :
This will push 3 on the stack and compute sq and sqrt :
<lang Oforth>3 dup sq swap sqrt</lang>
<syntaxhighlight lang="oforth">3 dup sq swap sqrt</syntaxhighlight>


=={{header|PARI/GP}}==
=={{header|PARI/GP}}==


gp is a REPL for GP, within which <code>%</code> can be used to refer to the last result.
gp is a REPL for GP, within which <code>%</code> can be used to refer to the last result.
<lang parigp>3
<syntaxhighlight lang="parigp">3
[sqrt(%),%^2]</lang>
[sqrt(%),%^2]</syntaxhighlight>
{{out}}
{{out}}
<pre>%1 = 3
<pre>%1 = 3
Line 373: Line 390:
It is the default parameter for loops, and some functions e.g. 'sqrt':
It is the default parameter for loops, and some functions e.g. 'sqrt':


<lang Perl>print sqrt . " " for (4, 16, 64)</lang>
<syntaxhighlight lang="perl">print sqrt . " " for (4, 16, 64)</syntaxhighlight>
{{out}}
{{out}}
<pre>2 4 8</pre>
<pre>2 4 8</pre>
Line 381: Line 398:
and the 'local' keyword is needed to enable loops to nest.
and the 'local' keyword is needed to enable loops to nest.


<lang perl>for (1..2) {
<syntaxhighlight lang="perl">for (1..2) {
print "outer $_:\n";
print "outer $_:\n";
local $_;
local $_;
Line 388: Line 405:
}
}
print " fini\n";
print " fini\n";
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>outer 1:
<pre>outer 1:
Line 397: Line 414:
=={{header|Phix}}==
=={{header|Phix}}==
The closest thing would be to declare a variable with just an underscore as its identifier.
The closest thing would be to declare a variable with just an underscore as its identifier.
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>object _
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
_ = 3
<span style="color: #004080;">object</span> <span style="color: #000000;">_</span>
?_
<span style="color: #000000;">_</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">3</span>
?_*_</lang>
<span style="color: #0000FF;">?</span><span style="color: #000000;">_</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">_</span><span style="color: #0000FF;">*</span><span style="color: #000000;">_</span>
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre>
<pre>
Line 408: Line 428:


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<lang PicoLisp>PicoLisp sets the value of the variable (symbol) '@' to the result of
<syntaxhighlight lang="picolisp">PicoLisp sets the value of the variable (symbol) '@' to the result of
conditional and controlling expressions in flow- and logic-functions (cond, if,
conditional and controlling expressions in flow- and logic-functions (cond, if,
and, when, while, etc.).
and, when, while, etc.).
Line 416: Line 436:


For example, to read the current input channel until EOF, and print the square
For example, to read the current input channel until EOF, and print the square
of every item which is a number:</lang>
of every item which is a number:</syntaxhighlight>
Test:
Test:
<lang PicoLisp>(while (read)
<syntaxhighlight lang="picolisp">(while (read)
(when (num? @)
(when (num? @)
(println (* @ @)) ) )
(println (* @ @)) ) )
Line 426: Line 446:
xyz # Not a number
xyz # Not a number
3 # Number
3 # Number
9 # -> print square</lang>
9 # -> print square</syntaxhighlight>


=={{header|PowerShell}}==
=={{header|PowerShell}}==
Line 435: Line 455:


The most common use is in the <code>ForEach-Object</code> cmdlet:
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 {$_ * 2} # Multiply the numbers by 2
65..67 | ForEach-Object {[char]$_ } # ASCII values of the numbers
65..67 | ForEach-Object {[char]$_ } # ASCII values of the numbers
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>
<pre>
Line 449: Line 469:
</pre>
</pre>
Using <code>Where-Object</code> to filter the odd numbers from an array:
Using <code>Where-Object</code> to filter the odd numbers from an array:
<syntaxhighlight lang="powershell">
<lang PowerShell>
65..67 | Where-Object {$_ % 2}
65..67 | Where-Object {$_ % 2}
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>
<pre>
Line 458: Line 478:
</pre>
</pre>
Using <code>Format-Wide</code> to force an array into columns:
Using <code>Format-Wide</code> to force an array into columns:
<syntaxhighlight lang="powershell">
<lang PowerShell>
65..70 | Format-Wide {$_} -Column 3 -Force
65..70 | Format-Wide {$_} -Column 3 -Force
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>
<pre>
Line 469: Line 489:
=={{header|Python}}==
=={{header|Python}}==
Pythons REPL has '''_'''.
Pythons REPL has '''_'''.
<lang python>>>> 3
<syntaxhighlight lang="python">>>> 3
3
3
>>> _*_, _**0.5
>>> _*_, _**0.5
(9, 1.7320508075688772)
(9, 1.7320508075688772)
>>> </lang>
>>> </syntaxhighlight>


=={{header|Racket}}==
=={{header|Racket}}==
Line 479: Line 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...)
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...)


<lang racket>
<syntaxhighlight lang="racket">
#lang racket
#lang racket


Line 537: Line 557:
)
)
(require 'sample2)
(require 'sample2)
</syntaxhighlight>
</lang>


=={{header|Raku}}==
=={{header|Raku}}==
Line 544: Line 564:
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:
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:


<lang perl6>$_ = 'Outside';
<syntaxhighlight lang="raku" line>$_ = 'Outside';
for <3 5 7 10> {
for <3 5 7 10> {
print $_;
print $_;
.³.map: { say join "\t", '', $_, .², .sqrt, .log(2), OUTER::<$_>, UNIT::<$_> }
.³.map: { say join "\t", '', $_, .², .sqrt, .log(2), OUTER::<$_>, UNIT::<$_> }
}</lang>
}</syntaxhighlight>
{{Out}}
{{Out}}
<pre>3 27 729 5.196152422706632 4.754887502163469 3 Outside
<pre>3 27 729 5.196152422706632 4.754887502163469 3 Outside
Line 562: Line 582:
=={{header|REXX}}==
=={{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.
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.
<lang rexx>/*REXX program shows something close to a "topic variable" (for functions/subroutines).*/
<syntaxhighlight lang="rexx">/*REXX program shows something close to a "topic variable" (for functions/subroutines).*/
parse arg N /*obtain a variable from the cmd line. */
parse arg N /*obtain a variable from the cmd line. */
call squareIt N /*invoke a function to square da number*/
call squareIt N /*invoke a function to square da number*/
Line 568: Line 588:
exit 0 /*stick a fork in it, we're all done. */
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
squareIt: return arg(1) ** 2 /*return the square of passed argument.*/</lang>
squareIt: return arg(1) ** 2 /*return the square of passed argument.*/</syntaxhighlight>
{{out|output|text=&nbsp; when using the input of: &nbsp; &nbsp; <tt> 12 </tt>}}
{{out|output|text=&nbsp; when using the input of: &nbsp; &nbsp; <tt> 12 </tt>}}
<pre>
<pre>
Line 575: Line 595:


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
see "sum1 = " + sum1(1,2) + nl
see "sum1 = " + sum1(1,2) + nl
see "sum2 = " + sum2(2,3) + nl
see "sum2 = " + sum2(2,3) + nl
Line 585: Line 605:
func sum2 (x, y)
func sum2 (x, y)
return x + y
return x + y
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
Line 595: Line 615:
In Ruby the topic variable is $_ (same as Perl).
In Ruby the topic variable is $_ (same as Perl).


<lang ruby>while DATA.gets # assigns to $_ (local scope)
<syntaxhighlight lang="ruby">while DATA.gets # assigns to $_ (local scope)
print # If no arguments are given, prints $_
print # If no arguments are given, prints $_
end
end
Line 601: Line 621:
This is line one
This is line one
This is line two
This is line two
This is line three</lang>
This is line three</syntaxhighlight>


{{out}}
{{out}}
Line 610: Line 630:
</pre>
</pre>
'''example:'''
'''example:'''
<lang ruby>DATA.gets
<syntaxhighlight lang="ruby">DATA.gets
p [$_.to_i ** 2, Math.sqrt($_.to_i)] #=> [9, 1.7320508075688772]
p [$_.to_i ** 2, Math.sqrt($_.to_i)] #=> [9, 1.7320508075688772]
__END__
__END__
3</lang>
3</syntaxhighlight>
The style of programming using $_ as an implicit parameter is gradually losing favor in the Ruby community.
The style of programming using $_ as an implicit parameter is gradually losing favor in the Ruby community.


=={{header|Scala}}==
=={{header|Scala}}==
<lang scala>object TopicVar extends App {
<syntaxhighlight lang="scala">object TopicVar extends App {
class SuperString(val org: String){
class SuperString(val org: String){
def it(): Unit = println(org)
def it(): Unit = println(org)
Line 629: Line 649:
Seq(4).foreach { it => println(it)}
Seq(4).foreach { it => println(it)}
Seq(8).foreach { it => println(it + it)}
Seq(8).foreach { it => println(it + it)}
}</lang>
}</syntaxhighlight>


=={{header|Sidef}}==
=={{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''
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''
<lang ruby>say [9,16,25].map {.sqrt}; # prints: [3, 4, 5]</lang>
<syntaxhighlight lang="ruby">say [9,16,25].map {.sqrt}; # prints: [3, 4, 5]</syntaxhighlight>


=={{header|Standard ML}}==
=={{header|Standard ML}}==
Line 640: Line 660:
expression in the REPL (as opposed to a declaration).
expression in the REPL (as opposed to a declaration).


<lang sml>- 3.0;
<syntaxhighlight lang="sml">- 3.0;
val it = 3.0 : real
val it = 3.0 : real
- it * it;
- it * it;
Line 646: Line 666:
- Math.sqrt it;
- Math.sqrt it;
val it = 3.0 : real
val it = 3.0 : real
-</lang>
-</syntaxhighlight>


=={{header|Tailspin}}==
=={{header|Tailspin}}==
Line 652: Line 672:
The current value goes through a sequence of transformations and has the new transformed value at each stage of the chain.
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.
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.
<lang tailspin>
<syntaxhighlight lang="tailspin">
3 -> \($-1! $+1!\) -> $*$ -> [$-1..$+1] -> '$;
3 -> \($-1! $+1!\) -> $*$ -> [$-1..$+1] -> '$;
' -> !OUT::write
' -> !OUT::write
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 666: Line 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:
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:


<lang sh>multiply 3 4 # We assume this user defined function has been previously defined
<syntaxhighlight 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</lang>
echo $? # This will output 12, but $? will now be zero indicating a successful echo</syntaxhighlight>


=={{header|VBA}}==
=={{header|VBA}}==
Line 676: Line 696:


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.
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.
<lang ecmascript>var T // global scope
<syntaxhighlight lang="wren">var T // global scope


var doSomethingWithT = Fn.new { [T * T, T.sqrt] }
var doSomethingWithT = Fn.new { [T * T, T.sqrt] }


T = 3
T = 3
System.print(doSomethingWithT.call())</lang>
System.print(doSomethingWithT.call())</syntaxhighlight>


{{out}}
{{out}}
Line 690: Line 710:
=={{header|zkl}}==
=={{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.
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.
<lang zkl>a,_,c:=List(1,2,3,4,5,6) //-->a=1, c=3, here _ is used as "ignore"
<syntaxhighlight 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
3.0 : _.sqrt() : println(_) //-->"1.73205", _ (and :) is used to "explode" a computation
// as syntactic sugar
// as syntactic sugar
1.0 + 2 : _.sqrt() : _.pow(4) // no variables used, the compiler "implodes" the computation
1.0 + 2 : _.sqrt() : _.pow(4) // no variables used, the compiler "implodes" the computation
// --> 9
// --> 9
</syntaxhighlight>
</lang>


{{omit from|BASIC}}
{{omit from|BASIC}}
{{omit from|C}}
{{omit from|C}}
{{omit from|C++}}
{{omit from|D}}
{{omit from|D}}
{{omit from|Delphi}}
{{omit from|Delphi}}
{{omit from|Free Pascal}}
{{omit from|Free Pascal}}
{{omit from|GUISS|Does not have any variables}}
{{omit from|GUISS|Does not have any variables}}
{{omit from|Microsoft Small Basic}}
{{omit from|OCaml}}
{{omit from|OCaml}}
{{omit from|Pascal}}
{{omit from|Pascal}}

Latest revision as of 14:53, 14 February 2024

Task
Topic variable
You are encouraged to solve this task according to the task description, using any language you may know.

Several programming languages offer syntax shortcuts to deal with the notion of "current" or "topic" variable.

A topic variable is a 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 to it and then computing its square and square root.

AppleScript

AppleScript binds the name result to the value of the expression most recently evaluated in the current scope.

on run
    1 + 2
    
    ap({square, squareRoot}, {result})
    
    --> {9, 1.732050807569}
end run


-- square :: Num a => a -> a
on square(x)
    x * x
end square

-- squareRoot :: Num a, Float b => a -> b
on squareRoot(x)
    x ^ 0.5
end squareRoot


-- GENERIC FUNCTIONS ----------------------------------------------------------

-- A list of functions applied to a list of arguments
-- (<*> | ap) :: [(a -> b)] -> [a] -> [b]
on ap(fs, xs)
    set lst to {}
    repeat with f in fs
        tell mReturn(contents of f)
            repeat with x in xs
                set end of lst to |λ|(contents of x)
            end repeat
        end tell
    end repeat
    return lst
end ap

-- Lift 2nd class handler function into 1st class script wrapper 
-- mReturn :: Handler -> Script
on mReturn(f)
    if class of f is script then
        f
    else
        script
            property |λ| : f
        end script
    end if
end mReturn
Output:
{9, 1.732050807569}

The name result is still bound in this way if the most recently evaluated expression is a script rather than a simple value:

on run
    script
        -- The given function applied to the value 3
        on |λ|(f)
            mReturn(f)'s |λ|(3)
        end |λ|
    end script
    
    -- Here, 'result' is bound to the script above
    map(result, {square, squareRoot})
    
    --> {9, 1.732050807569}
end run


-- square :: Num a => a -> a
on square(x)
    x * x
end square

-- squareRoot :: Num a, Float b => a -> b
on squareRoot(x)
    x ^ 0.5
end squareRoot


-- GENERIC FUNCTIONS ----------------------------------------------------------

-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
    tell mReturn(f)
        set lng to length of xs
        set lst to {}
        repeat with i from 1 to lng
            set end of lst to |λ|(item i of xs, i, xs)
        end repeat
        return lst
    end tell
end map

-- Lift 2nd class handler function into 1st class script wrapper 
-- mReturn :: Handler -> Script
on mReturn(f)
    if class of f is script then
        f
    else
        script
            property |λ| : f
        end script
    end if
end mReturn
Output:
{9, 1.732050807569}

Axe

In Axe, evaluated expressions can be "remembered" until the next expression is evaluated.

3
Disp *3▶Dec,i

Prints:

    9

However, attempting to use the result now would result in garbage due to the ▶Dec and Disp commands overwriting the previous result.

BASIC256

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)

Clojure

The Clojure REPL has *1 (and also *2 and *3 for the 2nd or 3rd most recent)

user=> 3
3
user=> (Math/pow *1 2)
9.0
user=> (Math/pow *2 0.5)
1.7320508075688772

Erlang

There are no global variables, so Erlang uses a function, v(N), to get old results. Either the absolute command result, if N is positive, or, if N is negative, the return value of the Nth previous command.

Output:
7> 1 + 2.
3
8> v(-1).
3

Forth

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.

: myloop 11 1 do i . loop cr ; myloop

Which will print all numbers from 1 to 10. A typical use of R@ is illustrated here:

: ^2 dup * ;
: sqrt 0 tuck ?do 1+ dup 2* 1+ +loop ;
: topic >r r@ ^2 . r@ sqrt . r> drop ;

23 topic

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.

FreeBASIC

The nearest thing FreeBASIC has to a topic variable is the name of the current function.

For example, if you declare a function called 'func' with a return type of Integer, the function behaves as though it contains a local variable called 'func' - defined at the top of its body - of type Integer. You can assign to this variable and, if you do, the return value of the function is the value this variable has when the function returns.

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.

' FB 1.05.0 Win64

' Three different ways of returning a value from a function

Function Sum (x As Integer, y As Integer) As Integer
  Sum = x + y  '' using name of function
End Function

Function Sum2 (x As Integer, y As Integer) As Integer
  Function = x + y  '' using Function keyword
End Function

Function Sum3 (x As Integer, y As Integer) As Integer
  Return x + y  '' using Return keyword which always returns immediately
End Function

Print Sum (1, 2)
Print Sum2(2, 3)
Print Sum3(3, 4)
Sleep
Output:
 3
 5
 7

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.

package main

import (
    "math"
    "os"
    "strconv"
    "text/template"
)

func sqr(x string) string {
    f, err := strconv.ParseFloat(x, 64)
    if err != nil {
        return "NA"
    }
    return strconv.FormatFloat(f*f, 'f', -1, 64)
}

func sqrt(x string) string {
    f, err := strconv.ParseFloat(x, 64)
    if err != nil {
        return "NA"
    }
    return strconv.FormatFloat(math.Sqrt(f), 'f', -1, 64)
}

func main() {
    f := template.FuncMap{"sqr": sqr, "sqrt": sqrt}
    t := template.Must(template.New("").Funcs(f).Parse(`. = {{.}}
square: {{sqr .}}
square root: {{sqrt .}}
`))
    t.Execute(os.Stdout, "3")
}
Output:
. = 3
square: 9
square root: 1.7320508075688772

Haskell

In Haskell terminal GHCi or WinGHCi, topic variable is called: it.

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]

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.

Thus, for example (entirely eliminating the variable representing the argument):

   example=: *:, %:  NB. *: is square, %: is square root
   example 3
9 1.73205

Or, if we want to see the dummy variable in place (though still not declared, because there is no point to that):

   Example=: verb def '(*: y), (%: y)'
   Example 3
9 1.73205

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.

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:

   (*:, %:) 3
9 1.73205

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 Tacit Programs.

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 ex can always be written simply as "exp".

There are some special character combinations involving ".":

  • .[] is a filter which expects the input to be an array or a JSON object, and converts the input to be a stream of the constituent values;
  • if i as an integer then .[i] is a filter which expects the input to be an array, and which extracts its i-th element (counting from 0).

Multiple references to the current input are allowed, e.g. [.,.] constructs an array of length two, each component being equal to the current input; thus the compound expression "1 | [.,.]" yields [1,1].

Julia

Julia REPL has `ans` variable:

julia> 3
3
julia> ans * ans, ans - 1
(9, 2)

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.

// version 1.1.2

fun main(args: Array<String>) {
    3.let {
        println(it)
        println(it * it)
        println(Math.sqrt(it.toDouble()))
    }
}
Output:
3
9
1.7320508075688772

Mathematica/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:

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

In this, I use 3 different forms. Here's a list of them:

  • %<n>: Does the same as Out[n].
  • %, %%, %%%, etc.: Does the same as Out[-<number of %s>].
  • Out[n]: Returns the output of the nth cell.
  • Out[-n]: Returns the output of the nth to last cell, excluding the one that it is in. (Out[-1] gives last output, -2 gives second to last, etc.)
  • In[n]: Reevaluates and returns the input of the nth cell.
  • In[-n]: Reevaluates and returns the input of the nth to last cell.

When an input is reevaluated, it also reassigns all relative Ins and Outs. Look at this for an example of its strange effects:

In[1]:= In[2]
Out[1]= In[2]

In[2]:= In[1]
$IterationLimit::itlim: Iteration limit of 4096 exceeded.
Out[2]= Hold[In[1]]

In it, it gets stuck in an infinite loop between In[1] and In[2], which evaluate to each other.

Nim

In Nim, the special variable _ may be considered as a topic variable. It is mainly used in loops when the value of the counter is not needed, for instance:

for _ in 1..10:
  echo "Hello World!"

Another kind of topic variable is it which is used in expressions in some templates. For instance:

import sequtils
let x = [1, 2, 3, 4, 5]
let y = x.mapIt(it * it)
echo y    # @[1, 4, 9, 16, 25]

Oforth

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 :

3 dup sq swap sqrt

PARI/GP

gp is a REPL for GP, within which % can be used to refer to the last result.

3
[sqrt(%),%^2]
Output:
%1 = 3
%2 = [1.7320508075688772935274463415058723670, 9]

Perl

In Perl the topic variable is $_. It is the default parameter for loops, and some functions e.g. 'sqrt':

print sqrt . " " for (4, 16, 64)
Output:
2 4 8

The topic variable is lexical, so its use can be nested into lexical scopes. However, assignment to the topic variable at loop declaration is not lexical, and the 'local' keyword is needed to enable loops to nest.

for (1..2) {
  print "outer $_:\n";
  local $_;
  for (1..3) {
    print " inner $_,";
  }
  print " fini\n";
}
Output:
outer 1:
 inner 1, inner 2, inner 3, fini
outer 2:
 inner 1, inner 2, inner 3, fini

Phix

The closest thing would be to declare a variable with just an underscore as its identifier.

with javascript_semantics
object _
_ = 3
?_
?_*_
Output:
3
9

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.).

Within a function or method '@' behaves like a local variable, i.e. its value is
automatically saved upon function entry and restored at exit.

For example, to read the current input channel until EOF, and print the square
of every item which is a number:

Test:

(while (read)
   (when (num? @)
      (println (* @ @)) ) )
abc   # Not a number
7     # Number
49    # -> print square
xyz   # Not a number
3     # Number
9     # -> print square

PowerShell

In PowerShell the "topic" variable is $_.

$_ is a placeholder for each object in the pipeline. Any cmdlet or advanced function that accepts input from the pipeline may use this variable.


The most common use is in the ForEach-Object cmdlet:

65..67 | ForEach-Object {$_ * 2}     # Multiply the numbers by 2
65..67 | ForEach-Object {[char]$_ }  # ASCII values of the numbers
Output:
130
132
134
A
B
C

Using Where-Object to filter the odd numbers from an array:

65..67 | Where-Object {$_ % 2}
Output:
65
67

Using Format-Wide to force an array into columns:

65..70 | Format-Wide {$_} -Column 3 -Force
Output:
65                                           66                                           67                                         
68                                           69                                           70                                         

Python

Pythons REPL has _.

>>> 3
3
>>> _*_, _**0.5
(9, 1.7320508075688772)
>>>

Racket

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...)

#lang racket

(module topic1 racket
  ;; define $ as a "parameter", but make it look like a plain identifier
  (provide $ (rename-out [$if if] [$#%app #%app]))
  (define current-value (make-parameter #f))
  (define-syntax $
    (syntax-id-rules (set!)
      [(_ x ...) ((current-value) x ...)]
      [(set! _ val) (current-value val)]
      [_ (current-value)]))
  ;; make an `if' form that binds it to the condition result
  (define-syntax-rule ($if C T E)
    (parameterize ([current-value C])
      (if $ T E)))
  ;; function application with []s uses the topic variable for the first arg
  (define-syntax ($#%app stx)
    (syntax-case stx ()
      [(_ f x y ...) (equal? #\[ (syntax-property stx 'paren-shape))
       #'(parameterize ([current-value x]) (f y ...))]
      [(_ f x ...) #'(f x ...)])))

(module topic2 racket
  ;; better variant: define `$' as a syntax parameter, which is adjusted to an
  ;; actual local binding; make it work in `if', and have a function definition
  ;; form that binds it to the actual arguments
  (provide $ (rename-out [$if if]) defun)
  (require racket/stxparam)
  (define-syntax-parameter $ (λ(stx) (raise-syntax-error '$ "not in scope")))
  (define-syntax-rule ($if C T E)
    (let ([c C]) (syntax-parameterize ([$ (make-rename-transformer #'c)])
                   (if c T E))))
  (define-syntax-rule (defun name body ...)
    (define (name arg)
      (syntax-parameterize ([$ (make-rename-transformer #'arg)])
        body ...)))
  )

(module sample1 racket
  (require (submod ".." topic1))
  (if (memq 2 '(1 2 3)) (cadr $) 'missing)
  ;; => 3
  (define (foo) (list (sqrt $) (* $ $)))
  [foo 9]
  ;; => '(3 81)
  )
(require 'sample1)

(module sample2 racket
  (require (submod ".." topic2))
  (if (memq 2 '(1 2 3)) (cadr $) 'missing)
  ;; => 3
  (defun foo (list (sqrt $) (* $ $)))
  (foo 9)
  ;; => '(3 81)
  )
(require 'sample2)

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:

$_ = 'Outside';
for <3 5 7 10> {
    print $_;
    .³.map: { say join "\t", '', $_, .², .sqrt, .log(2), OUTER::<$_>, UNIT::<$_>  }
}
Output:
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

Note: that the $_ inside the 'map' block is different than the $_ set in the 'for' block. The scope of the $_ variable is always lexical in Raku, though a function can access topics in other scopes by specifying the scope: CALLER::<$_> from within a subroutine, OUTER::<$_> for the next enclosing block, UNIT::<$_> for the outermost block in a compilation unit, etc. The scope modifiers may be stacked: CALLER::OUTER::<$_> 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.

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.

/*REXX program shows something close to a  "topic variable" (for functions/subroutines).*/
parse arg N                                      /*obtain a variable from the cmd line. */
call  squareIt N                                 /*invoke a function to square da number*/
say   result       '  ◄───'                      /*display returned value from the func.*/
exit 0                                           /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
squareIt:  return  arg(1) ** 2                   /*return the square of passed argument.*/
output   when using the input of:     12
144   ◄───

Ring

see "sum1 = " + sum1(1,2) + nl
see "sum2 = " + sum2(2,3) + nl

func sum1 (x, y) 
     sum = x + y 
     return sum
 
func sum2 (x, y) 
     return x + y

Output:

sum1 = 3
sum2 = 5

Ruby

In Ruby the topic variable is $_ (same as Perl).

while DATA.gets     # assigns to $_ (local scope)
  print             # If no arguments are given, prints $_
end
__END__
This is line one
This is line two
This is line three
Output:
This is line one
This is line two
This is line three

example:

DATA.gets
p [$_.to_i ** 2, Math.sqrt($_.to_i)]        #=> [9, 1.7320508075688772]
__END__
3

The style of programming using $_ as an implicit parameter is gradually losing favor in the Ruby community.

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)}
}

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

say [9,16,25].map {.sqrt};   # prints: [3, 4, 5]

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 it which is bound any time the user types an expression in the REPL (as opposed to a declaration).

- 3.0;
val it = 3.0 : real
- it * it;
val it = 9.0 : real
- Math.sqrt it;
val it = 3.0 : real
-

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.

3 -> \($-1! $+1!\) -> $*$ -> [$-1..$+1] -> '$;
' -> !OUT::write
Output:
[3, 4, 5]
[15, 16, 17]

UNIX Shell

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:

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

VBA

VBA does not have special or topic variables. All variables have a letter as their first character.

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.

var T // global scope

var doSomethingWithT = Fn.new { [T * T, T.sqrt] }

T = 3
System.print(doSomethingWithT.call())
Output:
[9, 1.7320508075689]

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.

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