Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What concept is involved here? Example in Python and R.

I am trying to find the right language to describe the following concept. Maybe someone can help me out.

This is a general question about programming but I'll use Python and R for examples.

In Python, we can put something in a dictionary like this

myData = {}
myData["myField"] = 14

In R, for example, using the data.table package, we could write something like

data = data.table(x = c(1, 2, 3))
data[,myField: = x^2]

These do different things but compare the second line of each of them. In Python, the "myField" is a string. In the R data.table example, there is no string. The R example is kinda nice because it saves you typing but then it gives you trouble if want to write a program where myField is a variable. In Python that is trivial because you can just do

myData[myVariable] = 14

with myVariable being defined as another string. In R, you can do this too but have to use a different syntax which means you have to know two completely different syntactical ways of programming it.

My question: What is this called? I know it has something to do with scoping rules, (perhaps meta programming?), but can't figure out the right language for it. Anyone?

like image 996
Dave31415 Avatar asked Jan 27 '14 16:01

Dave31415


1 Answers

I believe this programming language "feature" is known as "bare strings".

PHP also has (deprecated) support for this: Why is $foo[bar] wrong?

It's widely considered to be a pretty terrible idea because of the risk of overlap with variable or constant names, and should definitely be avoided in production code. However, JavaScript has an interesting twist on the idea that avoids those issues:

var obj = { key: "value" };

You can define the keys on inline objects without using quotation marks. This works because you can't do it the other way - the key is parsed as a string, never a variable name. I've found this to be a pretty useful tradeoff in programs where you only use predefined keys in dictionaries. The Python version, for reference, requires the quotation marks, but allows you to use a variable, as you demonstrated:

obj = { "key": "value", key_var: "value" }
like image 54
robbles Avatar answered Oct 21 '22 21:10

robbles