Dynamic variable names: Difference between revisions

Added Algol 68
m (Update lang example: Remove deprecated function)
(Added Algol 68)
 
(7 intermediate revisions by 4 users not shown)
Line 12:
*   [[Eval in environment]] is a similar task.
<br><br>
 
=={{header|ALGOL 68}}==
{{Trans|FreeBasic}}
This follows the FreeBASIC sample and simulates dynamic variable names using an array of name and values (both STRINGs).<br/>
Note, Algol 68G has a non-standard <code>to lower</code> procedure, which could be used in the LCASE operator, i.e.: <code>OP LCASE = ( CHAR c )CHAR: to lower( c );</code>.
<syntaxhighlight lang="algol68">
BEGIN # Simulate dynamic variables using an array, translation of the FreeBASIC sample #
 
MODE DYNAMICVARIABLE = STRUCT( STRING name, value );
 
OP LCASE = ( CHAR c )CHAR: IF c >= "A" AND c <= "Z" THEN REPR( ( ABS c - ABS "A" ) + ABS "a" ) ELSE c FI;
OP LCASE = ( STRING s )STRING:
BEGIN
STRING lc := s;
FOR i FROM LWB lc TO UPB lc DO lc[ i ] := LCASE lc[ i ] OD;
lc
END # LCASE # ;
OP TRIM = ( STRING s )STRING:
BEGIN
INT left := LWB s, right := UPB s;
WHILE IF left > right THEN FALSE ELSE s[ left ] = " " FI DO left +:= 1 OD;
WHILE IF right < left THEN FALSE ELSE s[ right ] = " " FI DO right -:= 1 OD;
s[ left : right ]
END # TRIM # ;
 
PROC find variable index = ( []DYNAMICVARIABLE a, STRING v, INT n elements )INT:
BEGIN
STRING name = LCASE TRIM v;
INT index := LWB a - 1;
INT max index = index + n elements;
FOR i FROM LWB a TO max index WHILE index < LWB a DO
IF name OF a[ i ] = name THEN index := i FI
OD;
index
END # find variable index # ;
 
INT n;
WHILE
print( ( "How many variables do you want to create (max 5) " ) );
read( ( n, newline ) );
n < 0 OR n > 5
DO SKIP OD;
 
[ 1 : n ]DYNAMICVARIABLE a;
 
print( ( newline, "OK, enter the variable names and their values, below", newline ) );
 
FOR i TO n DO
WHILE
print( ( " Variable ", whole( i, 0 ), newline ) );
print( ( " Name : " ) );
read( ( name OF a[ i ], newline ) );
name OF a[ i ] := LCASE TRIM name OF a[ i ];
# identifiers should not be case-sensitive in Algol 68 though #
# in upper stropped sources (such as this one) they have to #
# be in lower case #
find variable index( a, name OF a[ i ], i - 1 ) > 0
DO
print( ( " Sorry, you've already created a variable of that name, try again", newline ) )
OD;
print( ( " Value : " ) );
read( ( value OF a[ i ], newline ) );
value OF a[ i ] := TRIM value OF a[ i ]
OD;
 
print( ( newline, "Press q to quit" ) );
WHILE
STRING v;
print( ( newline, "Which variable do you want to inspect ? " ) );
read( ( v, newline ) );
v /= "q" AND v /= "Q"
DO
IF INT index = find variable index( a, v, n );
index = 0
THEN
print( ( "Sorry there's no variable of that name, try again", newline ) )
ELSE
print( ( "It's value is ", value OF a[ index ], newline ) )
FI
OD
 
END
</syntaxhighlight>
{{out}}
<pre>
How many variables do you want to create (max 5) 3
 
OK, enter the variable names and their values, below
Variable 1
Name : v1
Value : 123
Variable 2
Name : abc
Value : mnop
Variable 3
Name : l3
Value : 21
 
Press q to quit
Which variable do you want to inspect ? L3
It's value is 21
 
Which variable do you want to inspect ? MNOP
Sorry there's no variable of that name, try again
 
Which variable do you want to inspect ? AbC
It's value is mnop
 
Which variable do you want to inspect ? q
</pre>
 
=={{header|APL}}==
Line 167 ⟶ 277:
<pre>
Hello world!
</pre>
 
=={{header|C++}}==
C++ is a compiled language which means that it loses information about names in code in the compilation process of translation to machine code. This means you can't use any information from your code at runtime without manually storing it somewhere. We therefore simulate dynamic variables using an unordered_map.
<syntaxhighlight lang="c++">
#include <algorithm>
#include <cstdint>
#include <iostream>
#include <string>
#include <unordered_map>
 
int main() {
std::unordered_map<std::string, int32_t> variables;
 
std::string name;
std::cout << "Enter your variable name: " << std::endl;
std::cin >> name;
 
int32_t value;
std::cout << "Enter your variable value: " << std::endl;
std::cin >> value;
 
variables[name] = value;
 
std::cout << "You have created a variable '" << name << "' with a value of " << value << ":" << std::endl;
 
std::for_each(variables.begin(), variables.end(),
[](std::pair<std::string, int32_t> pair) {
std::cout << pair.first << " = " << pair.second << std::endl;
}
);
}
</syntaxhighlight>
{{ out }}
<pre>
Enter your variable name:
foo
Enter your variable value:
42
You have created a variable 'foo' with a value of 42:
foo = 42
</pre>
 
Line 258 ⟶ 409:
Dynamic variables are not supported by the language. But it is possible to set a dynamic property.
 
ELENA 56.0x :
<syntaxhighlight lang="elena">import system'dynamic;
import extensions;
Line 264 ⟶ 415:
class TestClass
{
object theVariablesvariables;
 
constructor()
{
theVariablesvariables := new DynamicStruct()
}
function()
{
auto prop := new MessageName(console.write:("Enter the variable name:").readLine());
(prop.setPropertyMessage())(theVariablesvariables,42);
console.printLine(prop.toPrintable(),"=",(prop.getPropertyMessage())(theVariablesvariables)).readChar()
}
}
 
public program = new TestClass();</syntaxhighlight>
The program should be compiled as a vm-client:
<pre>
elena-cli sandbox.l -tvm_console
</pre>
{{out}}
<pre>
Line 579 ⟶ 734:
 
{{omit cat|Unicon}}
 
=={{Header|Insitux}}==
 
This first approach creates a function that creates a variable of that name.
 
<syntaxhighlight lang="insitux">
(let var-name "hello")
((eval (str "(var " var-name ")")) 123)
</syntaxhighlight>
 
This second approach puts the variable value directly in the evaluated string.
 
<syntaxhighlight lang="insitux">
(let var-name "hello")
(eval (str "(var " var-name " 123)"))
</syntaxhighlight>
 
=={{header|J}}==
Line 1,443 ⟶ 1,614:
 
=={{header|Wren}}==
{{libheader|Wren-ioutil}}
Although Wren is dynamically typed, it is not possible to create new variables at run time. We therefore follow the example of some of the statically typed languages here and use a map instead.
{{libheader|Wren-trait}}
<syntaxhighlight lang="ecmascript">import "io" for Stdin, Stdout
Although Wren is dynamically typed, it is not possible to create new variables at run time. However, we can simulate this using a map which is what the Var class in Wren-trait does under the hood.
<syntaxhighlight lang="wren">import "./ioutil" for Input
import "./trait" for Var
 
var userVars = {}
System.print("Enter three variables:")
for (i in 0..2) {
Systemvar name = Input.writetext("\n name : ")
var value = Input.text(" value : ")
Stdout.flush()
var Var[name] = StdinNum.readLinefromString(value)
System.write(" value: ")
Stdout.flush()
var value = Num.fromString(Stdin.readLine())
userVars[name] = value
}
 
System.print("\nYour variables are:\n")
for (kv in userVarsVar.entries) {
System.print(" %(kv.key) = %(kv.value)")
}</syntaxhighlight>
Line 1,468 ⟶ 1,637:
Enter three variables:
 
name : pip
value : 3
 
name : squeak
value : 4
 
name : wilfred
value : 5
 
Your variables are:
3,034

edits