var1 = 1
var2 = var1 # why doesn't this bind the two variables?
var2 = var2 + 3
print(var1)
print(var2)
The output is
1
4
What is the Python 3.x (added after StackrunnethOver's original answer - apologies for not specifying) syntax to bind var2 to the same memory as var1? Not that I want to, but rather that I want to make sure that my assignment statements aren't accidentally binding two variables to one another.
This line of questioning (how do I know what happens to variables and when) is usually very language-dependent, so it’s often a lot more relevant to talk about it in the context of a specific language. However, in the example you present, I think there is a general answer:
For the code:
var1 = 1
var2 = var1
var2 = var2 + 3
On line 2, there are two things that could happen:
var2 gets assigned the value 1
var2 now points to the same location in memory as var1, and var1’s location in memory holds the value 1
If #1 happens, we get the behavior you see above. This should not be surprising.
If #2 happens, now var1 and var2 point to the same location in memory. Your question is why isn’t this the case? Consider, if line 2 does make var2 point to the same thing as var1, what does line 3 do?
...
If x = y makes x point to the thing y points to, what does x = y + 3 do? Make x point to the thing y + 3 points to? This doesn’t really make sense.
What this gets at, underneath, is the difference between a value, a variable, and a pointer. In the example you give, var1 and var2 are variables, which on the left hand side of an equals sign are treated as such (you can assign values to your variables e.g. x = 3). But on the right-hand side of an equals sign, variables become their values before other operations take place. In var2 = var1 + 3, the expression becomes var2 = 1 + 3 and then var2 = 4.
In some languages, this behavior is not always automatic. Instead, you have to create it for yourself, by using pointers. This effectively means you have one way of referencing a variable x which explicitly says you want the location in memory x points to, which is the true “value of x”, and another way of referencing it x’ which explicitly says you want the value at that location in memory.
In such a world, your code could be written as
var1’ = 1
var2’ = var1’
var2’ = var2’ + 3
To get behavior #1 above, or
var1’ = 1
var2 = var1
var2’ = var2’ + 3
To get output
4
4
All this assuming that var1 and var2 have been initialized beforehand.
In such languages (like C) you can actually do things like `x = y + 3’, where x and y are pointers. It literally makes x equal to the position in memory three spots further along than y. This is called pointer arithmetic.
Is there a way to introspect a variable to directly find out what subset it was declared with? Here I create a subset, but introspection points me to its base type:
> subset Prime of Int where .is-prime
(Prime)
> my Prime $x = 23
23
> $x.WHICH
Int|23
I know it has to store the information somewhere, because if I try to reassign a value that doesn't match the subset, it fails:
> $x = 24
Type check failed in assignment to $x; expected Prime but got Int (24)
in block <unit> at <unknown file> line 1
I tried searching through the code, but I quickly get down into files like container.c and perl6_ops.c where the C code makes my eyes glaze over. I thought that X::TypeCheck::Assignment might help (see core/Exception.pm), but it's not clear to me where the expected value comes from. (see also this commit)
I feel like I'm missing something obvious.
I can check that something matches a subset, but that doesn't tell me if it were declared with a particular subset:
> my Int $y = 43;
43
> $y ~~ Prime;
True
I'm using Rakudo Star 2017.01
Inspired by a Zoffix's use of subsets in a recent post.
The value that you stored in $x is an Int. It is acceptable to the container (which you typed to Prime) because Prime is a subtype of Int.
So what you're interested in, is not the value in the container, but the type of the container. To get at the container, Perl 6 has the .VAR method. And that has an .of method to get at the type:
$ 6 'subset Prime of Int where .is-prime; my Prime $x; dd $x.VAR.of'
Prime
Okay, I've looked on about 4-5 websites that offered to teach Haskell and not one of them explained the keyword aux. They just started using it. I've only really studied Java and C (never saw it in either if it exists), and I've never really encountered it before this class that I'm taking on Haskell. All I can really tell is that it provides the utility to create and store a value within a function. So what exactly does it do and how is it properly used and formatted? In particular, could you explain its use while recursing? I don't think that its use is any different, but just to make sure I thought I would ask.
There is no keyword aux, my guess is this is just the name they used for a local function.
Just like you can define top-level values:
myValue = 4
or top-level functions:
myFunction x = 2 * x
you can similarly define local values:
myValue =
let myLocalValue = 3 in
myLocalValue + 1
-- or equivalently:
myValue = myLocalValue + 1
where myLocalValue = 3
or a local function:
myValue =
let myLocalFunction x = 2 * x in
myLocalFunction 2
-- or equivalently:
myValue = myLocalFunction 2
where myLocalFunction x = 2 * x
Your teacher simply named the local function aux instead of myLocalFunction.
I am using R to parse a list of strings in the form:
original_string <- "variable_name=variable_value"
First, I extract the variable name and value from the original string and convert the value to numeric class.
parameter_value <- as.numeric("variable_value")
parameter_name <- "variable_name"
Then, I would like to assign the value to a variable with the same name as the parameter_name string.
variable_name <- parameter_value
What is/are the function(s) for doing this?
assign is what you are looking for.
assign("x", 5)
x
[1] 5
but buyer beware.
See R FAQ 7.21
http://cran.r-project.org/doc/FAQ/R-FAQ.html#How-can-I-turn-a-string-into-a-variable_003f
You can use do.call:
do.call("<-",list(parameter_name, parameter_value))
There is another simple solution found there:
http://www.r-bloggers.com/converting-a-string-to-a-variable-name-on-the-fly-and-vice-versa-in-r/
To convert a string to a variable:
x <- 42
eval(parse(text = "x"))
[1] 42
And the opposite:
x <- 42
deparse(substitute(x))
[1] "x"
The function you are looking for is get():
assign ("abc",5)
get("abc")
Confirming that the memory address is identical:
getabc <- get("abc")
pryr::address(abc) == pryr::address(getabc)
# [1] TRUE
Reference: R FAQ 7.21 How can I turn a string into a variable?
Use x=as.name("string"). You can use then use x to refer to the variable with name string.
I don't know, if it answers your question correctly.
strsplit to parse your input and, as Greg mentioned, assign to assign the variables.
original_string <- c("x=123", "y=456")
pairs <- strsplit(original_string, "=")
lapply(pairs, function(x) assign(x[1], as.numeric(x[2]), envir = globalenv()))
ls()
assign is good, but I have not found a function for referring back to the variable you've created in an automated script. (as.name seems to work the opposite way). More experienced coders will doubtless have a better solution, but this solution works and is slightly humorous perhaps, in that it gets R to write code for itself to execute.
Say I have just assigned value 5 to x (var.name <- "x"; assign(var.name, 5)) and I want to change the value to 6. If I am writing a script and don't know in advance what the variable name (var.name) will be (which seems to be the point of the assign function), I can't simply put x <- 6 because var.name might have been "y". So I do:
var.name <- "x"
#some other code...
assign(var.name, 5)
#some more code...
#write a script file (1 line in this case) that works with whatever variable name
write(paste0(var.name, " <- 6"), "tmp.R")
#source that script file
source("tmp.R")
#remove the script file for tidiness
file.remove("tmp.R")
x will be changed to 6, and if the variable name was anything other than "x", that variable will similarly have been changed to 6.
I was working with this a few days ago, and noticed that sometimes you will need to use the get() function to print the results of your variable.
ie :
varnames = c('jan', 'feb', 'march')
file_names = list_files('path to multiple csv files saved on drive')
assign(varnames[1], read.csv(file_names[1]) # This will assign the variable
From there, if you try to print the variable varnames[1], it returns 'jan'.
To work around this, you need to do
print(get(varnames[1]))
If you want to convert string to variable inside body of function, but you want to have variable global:
test <- function() {
do.call("<<-",list("vartest","xxx"))
}
test()
vartest
[1] "xxx"
Maybe I didn't understand your problem right, because of the simplicity of your example. To my understanding, you have a series of instructions stored in character vectors, and those instructions are very close to being properly formatted, except that you'd like to cast the right member to numeric.
If my understanding is right, I would like to propose a slightly different approach, that does not rely on splitting your original string, but directly evaluates your instruction (with a little improvement).
original_string <- "variable_name=\"10\"" # Your original instruction, but with an actual numeric on the right, stored as character.
library(magrittr) # Or library(tidyverse), but it seems a bit overkilled if the point is just to import pipe-stream operator
eval(parse(text=paste(eval(original_string), "%>% as.numeric")))
print(variable_name)
#[1] 10
Basically, what we are doing is that we 'improve' your instruction variable_name="10" so that it becomes variable_name="10" %>% as.numeric, which is an equivalent of variable_name=as.numeric("10") with magrittr pipe-stream syntax. Then we evaluate this expression within current environment.
Hope that helps someone who'd wander around here 8 years later ;-)
Other than assign, one other way to assign value to string named object is to access .GlobalEnv directly.
# Equivalent
assign('abc',3)
.GlobalEnv$'abc' = 3
Accessing .GlobalEnv gives some flexibility, and my use case was assigning values to a string-named list. For example,
.GlobalEnv$'x' = list()
.GlobalEnv$'x'[[2]] = 5 # works
var = 'x'
.GlobalEnv[[glue::glue('{var}')]][[2]] = 5 # programmatic names from glue()
I was wondering. Are there languages that use only pass-by-reference as their eval strategy?
I don't know what an "eval strategy" is, but Perl subroutine calls are pass-by-reference only.
sub change {
$_[0] = 10;
}
$x = 5;
change($x);
print $x; # prints "10"
change(0); # raises "Modification of a read-only value attempted" error
VB (pre .net), VBA & VBS default to ByRef although it can be overriden when calling/defining the sub or function.
FORTRAN does; well, preceding such concepts as pass-by-reference, one should probably say that it uses pass-by-address; a FORTRAN function like:
INTEGER FUNCTION MULTIPLY_TWO_INTS(A, B)
INTEGER A, B
MULTIPLY_BY_TWO_INTS = A * B
RETURN
will have a C-style prototype of:
extern int MULTIPLY_TWO_INTS(int *A, int *B);
and you could call it via something like:
int result, a = 1, b = 100;
result = MULTIPLY_TWO_INTS(&a, &b);
Another example are languages that do not know function arguments as such but use stacks. An example would be Forth and its derivatives, where a function can change the variable space (stack) in whichever way it wants, modifying existing elements as well as adding/removing elements. "prototype comments" in Forth usually look something like
(argument list -- return value list)
and that means the function takes/processes a certain, not necessarily constant, number of arguments and returns, again, not necessarily a constant, number of elements. I.e. you can have a function that takes a number N as argument and returns N elements - preallocating an array, if you so like.
How about Brainfuck?