Skip to content

Instantly share code, notes, and snippets.

@DrGo
Created March 17, 2018 18:28
Show Gist options
  • Save DrGo/0d0c32a2a1a282e4a2e15899ca3dc189 to your computer and use it in GitHub Desktop.
Save DrGo/0d0c32a2a1a282e4a2e15899ca3dc189 to your computer and use it in GitHub Desktop.
Signalling intentions in Stata using fake keywords

In Stata, it is possible to create pseudo-keywords to document your intentions. For instance, Stata does not have a way to declare a macro (Stata memory-based variable) as a constant. In many programming languages, there is a keyword, typically const, that signals to the compiler/interpreter, and more importantly to human readers, that this variable should not be changed after its declaration. E.g.,

    const PI = 3.14   //PI is guaranteed not to change during the execution of the program, avoiding subtle bugs

There is no equivalent keyword in Stata, but it can be simulated using this approach:

// In your profile.do, declare a global macro "const" and assign an empty string to it
global const ""

// now you could write
local $const PI=3.14

// use PI as usual, eg
display `PI' * 5^2

//output 78.5

I prefer this approach to this one:

// declare a global macro "lconst" and assign "local" to it
global lconst "local "

// now you could define a local const using
$lconst PI=3.14

// use PI as usual, eg
display `PI' * 5^2

//output 78.5

I think the first approach is clearer. Generally it is not recommended to create many fake keywords because it could result in diverging dialects of Stata, unfathomable but to their creators. But the judicial use of constructs like "const" can improve readability. And although variables declared using with the pseudo-keyword "const" are still regular Stata variables and can be changed at will, it is possible to write a tool (linter) to verify that variables declared are not changed anywhere in the program. Other possible uses include declaring macros of certain type, e.g., "String", "Float" or "Bool."

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment