Idiomatic way to avoid variable shadowing in Nim - naming-conventions

Suppose that I want to define a variable called sum, but the name collides with some predefined function. In Python, I would write something like _sum or sum_ to refer to the local variable. However, using underscore in Nim leads to an invalid token error. Is there an accepted naming convention to deal with such cases?

Change both to more descriptive names like sumProducts, sumHorses.

You are free a use a wide variety of characters, even unicode if you want. So below works:
proc sum(): int =
var ∑ = 42 # using ∑ as variable identifier
return ∑
echo sum() # -> 42
But def- has the right answer: Make the identifiers more descriptive.

Related

Is it possible to preserve variable names when writing and reading term programatically?

I'm trying to write an SWI-Prolog predicate that applies numbervars/3 to a term's anonymous variables but preserves the user-supplied names of its non-anonymous variables. I eventually plan on adding some kind of hook to term_expansion (or something like that).
Example of desired output:
?- TestList=[X,Y,Z,_,_].
> TestList=[X,Y,Z,A,B].
This answer to the question Converting Terms to Atoms preserving variable names in YAP prolog shows how to use read_term to obtain as atoms the names of the variables used in a term. This list (in the form [X='X',Y='Y',...]) does not contain the anonymous variables, unlike the variable list obtained by term_variables, making isolation of the anonymous variables fairly straightforward.
However, the usefulness of this great feature is somewhat limited if it can only be applied to terms read directly from the terminal. I noticed that all of the examples in the answer involve direct user input of the term. Is it possible to get (as atoms) the variable names for terms that are not obtained through direct user input? That is, is there some way to 'write' a term (preserving variable names) to some invisible stream and then 'read' it as if it were input from the terminal?
Alternatively... Perhaps this is more of a LaTeX-ish line of thinking, but is there some way to "wrap" variables inside single quotes (thereby atom-ifying them) before Prolog expands/tries to unify them as variables, with the end result that they're treated as atoms that start with uppercase letters rather than as variables?
You can use the ISO core standard variable_names/1 read and write option. Here is some example code, that replaces anonymous variables in a variable name mapping:
% replace_anon(+Map, +Map, -Map)
replace_anon([_=V|M], S, ['_'=V|N]) :- member(_=W, S), W==V, !,
replace_anon(M, S, N).
replace_anon([A=V|M], S, [A=V|N]) :-
replace_anon(M, S, N).
replace_anon([], _, []).
variable_names/1 is ISO core standard. It was always a read option. It then became a write option as well. See also: https://www.complang.tuwien.ac.at/ulrich/iso-prolog/WDCor3
Here is an example run:
Welcome to SWI-Prolog (threaded, 64 bits, version 7.7.25)
?- read_term(X,[variable_names(M),singletons(S)]),
replace_anon(M,S,N),
write_term(X,[variable_names(N)]).
|: p(X,Y,X).
p(X,_,X)
To use the old numbervars/3 is not recommended, since its not compatible with attribute variables. You cannot use it for example in the presence of CLP(FD).
Is it possible to get (as atoms) the variable names for terms that are not obtained through direct user input?
if you want to get variable names from source files you should read them from there.
The easiest way to do so using term expansion.
Solution:
read_term_from_atom(+Atom, -Term, +Options)
Use read_term/3 to read the next term from Atom.
Atom is either an atom or a string object.
It is not required for Atom to end with a full-stop.
Use Atom as input to read_term/2 using the option variable_names and return the read term in Term and the variable bindings in variable_names(Bindings).
Bindings is a list of Name = Var couples, thus providing access to the actual variable names. See also read_term/2.
If Atom has no valid syntax, a syntax_error exception is raised.
write_term( Term ) :-
numbervars(Term, 0, End),
write_canonical(Term), nl.

What does the operator := mean? [duplicate]

I've seen := used in several code samples, but never with an accompanying explanation. It's not exactly possible to google its use without knowing the proper name for it.
What does it do?
http://en.wikipedia.org/wiki/Equals_sign#In_computer_programming
In computer programming languages, the equals sign typically denotes either a boolean operator to test equality of values (e.g. as in Pascal or Eiffel), which is consistent with the symbol's usage in mathematics, or an assignment operator (e.g. as in C-like languages). Languages making the former choice often use a colon-equals (:=) or ≔ to denote their assignment operator. Languages making the latter choice often use a double equals sign (==) to denote their boolean equality operator.
Note: I found this by searching for colon equals operator
It's the assignment operator in Pascal and is often used in proofs and pseudo-code. It's the same thing as = in C-dialect languages.
Historically, computer science papers used = for equality comparisons and ← for assignments. Pascal used := to stand in for the hard-to-type left arrow. C went a different direction and instead decided on the = and == operators.
In the statically typed language Go := is initialization and assignment in one step. It is done to allow for interpreted-like creation of variables in a compiled language.
// Creates and assigns
answer := 42
// Creates and assigns
var answer = 42
Another interpretation from outside the world of programming languages comes from Wolfram Mathworld, et al:
If A and B are equal by definition (i.e., A is defined as B), then this is written symbolically as A=B, A:=B, or sometimes A≜B.
■ http://mathworld.wolfram.com/Defined.html
■ https://math.stackexchange.com/questions/182101/appropriate-notation-equiv-versus
Some language uses := to act as the assignment operator.
In a lot of CS books, it's used as the assignment operator, to differentiate from the equality operator =. In a lot of high level languages, though, assignment is = and equality is ==.
This is old (pascal) syntax for the assignment operator. It would be used like so:
a := 45;
It may be in other languages as well, probably in a similar use.
A number of programming languages, most notably Pascal and Ada, use a colon immediately followed by an equals sign (:=) as the assignment operator, to distinguish it from a single equals which is an equality test (C instead used a single equals as assignment, and a double equals as the equality test).
Reference: Colon (punctuation).
In Python:
Named Expressions (NAME := expr) was introduced in Python 3.8. It allows for the assignment of variables within an expression that is currently being evaluated. The colon equals operator := is sometimes called the walrus operator because, well, it looks like a walrus emoticon.
For example:
if any((comment := line).startswith('#') for line in lines):
print(f"First comment: {comment}")
else:
print("There are no comments")
This would be invalid if you swapped the := for =. Note the additional parentheses surrounding the named expression. Another example:
# Compute partial sums in a list comprehension
total = 0
values = [1, 2, 3, 4, 5]
partial_sums = [total := total + v for v in values]
# [1, 3, 6, 10, 15]
print(f"Total: {total}") # Total: 15
Note that the variable total is not local to the comprehension (so too is comment from the first example). The NAME in a named expression cannot be a local variable within an expression, so, for example, [i := 0 for i, j in stuff] would be invalid, because i is local to the list comprehension.
I've taken examples from the PEP 572 document - it's a good read! I for one am looking forward to using Named Expressions, once my company upgrades from Python 3.6. Hope this was helpful!
Sources: Towards Data Science Article and PEP 572.
It's like an arrow without using a less-than symbol <= so like everybody already said "assignment" operator. Bringing clarity to what is being set to where as opposed to the logical operator of equivalence.
In Mathematics it is like equals but A := B means A is defined as B, a triple bar equals can be used to say it's similar and equal by definition but not always the same thing.
Anyway I point to these other references that were probably in the minds of those that invented it, but it's really just that plane equals and less that equals were taken (or potentially easily confused with =<) and something new to define assignment was needed and that made the most sense.
Historical References: I first saw this in SmallTalk the original Object Language, of which SJ of Apple only copied the Windows part of and BG of Microsoft watered down from them further (single threaded). Eventually SJ in NeXT took the second more important lesson from Xerox PARC in, which became Objective C.
Well anyway they just took colon-equals assiment operator from ALGOL 1958 which was later popularized by Pascal
https://en.wikipedia.org/wiki/PARC_(company)
https://en.wikipedia.org/wiki/Assignment_(computer_science)
Assignments typically allow a variable to hold different values at
different times during its life-span and scope. However, some
languages (primarily strictly functional) do not allow that kind of
"destructive" reassignment, as it might imply changes of non-local
state.
The purpose is to enforce referential transparency, i.e. functions
that do not depend on the state of some variable(s), but produce the
same results for a given set of parametric inputs at any point in
time.
https://en.wikipedia.org/wiki/Referential_transparency
For VB.net,
a constructor (for this case, Me = this in Java):
Public ABC(int A, int B, int C){
Me.A = A;
Me.B = B;
Me.C = C;
}
when you create that object:
new ABC(C:=1, A:=2, B:=3)
Then, regardless of the order of the parameters, that ABC object has A=2, B=3, C=1
So, ya, very good practice for others to read your code effectively
Colon-equals was used in Algol and its descendants such as Pascal and Ada because it is as close as ASCII gets to a left-arrow symbol.
The strange convention of using equals for assignment and double-equals for comparison was started with the C language.
In Prolog, there is no distinction between assignment and the equality test.

How to consistently replace atoms with variables in Prolog?

I am writing a parser for SPARQL (Semantic Web query language) using DCG. I want to replace SPARQL variable names with Prolog variables. How would I go about this?
I can generate new variables using length([NewVar], 1), but I cannot keep track of existing assignments by simply using a list of name-variable pairs. A member/2 operation on the list will return a new variable, not the one stored in the list.
Is there an easy way for naming variables in Prolog, e.g., '$VAR(Name)'?
member/2 will do what you want. Here is an example:
Welcome to SWI-Prolog (Multi-threaded, 64 bits, Version 7.3.25)
Copyright (c) 1990-2016 University of Amsterdam, VU Amsterdam
L=[a-X,b-Y,c-Z], member(b-V,L).
L = [a-X, b-V, c-Z],
Y = V
But you might get problems if you interleave write/1 with member/2,
since a variable might change its identity, i.e. the write symbol in the following circumstances:
because of garbage collection, if a variable is written as _G<memloc>
because of aliasing, in the above example the memloc of V might be shown
instead of the memloc of Y
Same problem with (#<)/2. One way out is to use attribute variables, which at least puts an end to aliasing, since attribute variables are usually unified last,
so in the above example if Y is an attribute variable and V is an ordinary variable you would never see the memloc of V after
calling member/2.
Further you can also mitigate the problem by using ISO core standard variable_names/1 write option, to write out a variablified term. The variable_names/1 write option is immune to garbage collection or aliasing.
Bye

In lambda calculus, can variable be expression in general?

For better understanding of functional programming, I am reading the wiki page for lambda calculus here.
The definition says:
If x is a variable and M ∈ Λ, then (λx.M) ∈ Λ
Intuitively I thought variable are / represented by single-letter id's. But since here we deal with strict math definitions, I just want to double confirm this understanding: in general, can expression be classified as variable?
e.g. if x is a variable, is expression (x + x) a variable in lambda calculus? i.e. is it ok to write (λ(x+x).M) as an lambda calculus abstraction?
(Concern is in some context this is true. e.g. Here: An expression such as 4x^3 is a variable)
No, (x + x) is no variable (indeed it's not even a expression in naive lambda calculus).
I think you mix the terms variables and expressions somehow (or want some kind of pattern-matching?).
So let's follow the core-definition of lambda-calculus and expressions:
The definition itself is not that hard (indeed you linked it yourself with the wiki-page).
It's mentioned right from the start:
you have a set of variables V: (v_1, v_2, ...) (of course you can name them as you want - it's only important that you remmber that these are considered different symbols in your calculus)
the symbols λ, ., ( and )
This is it - thats all of the "Tokens" for this grammar/calculus.
Now there are a couple of rules how you can form Expressions from these:
each Variable is a expression
Abstraction: if E is a expression and x is a Variable then (λx.E) is a expression (here x and E are templates or Metavariables - you have to fill them with some real Expression to make this an Expression!)
Application: if A and B are expressions than (A B) is a expression.
So possible expressions are:
v_50
(λv_4.v_5)
((λv_4.v_5) v_50)
....
This is all when it comes to expressions.
You see: if you don't allow (x+x) as a symbol or name for a variable from the start it can never be a variable - indeed no expression is a variable even if there are some expressions consisting only of one said variable - if you called something expression it will never be a variable (again) ;)
PS: of course there are a couple of conventions to keep the parentheses a bit down - but for a start you don't need those.

Use NSPredicate to parse a formula with variables

Task:
I am planning to parse a formula string in NSPredicate and to replace variables in the string by their numeric values. The variables are names for properties of existing object instances in my data model, for instance I have a class "company" with an instance "Apple Corp."
Set-up:
My formula would like look like this: "Profitability_2011_in% = [Profit 2011] / [Revenue 2011]"
The instance "Apple Corp" would have the following properties:
Revenue 2009 = 10, Revenue 2010 = 20, Revenue 2011 = 30,
Profit 2009 = 5, Profit 2010 = 10, Profit 2011 = 20.
Hence, the formula would yield 20 / 30 = 67%.
Variables are usually two-dimensional, for instance defined by "profit" as the financial statement item and "year" (for instance 2011).
The variables are enclosed in [ ] and the dimensions are separated by " " (whitespace).
How I would do it
My implementation would begin with NSRegularExpression's matchesInString:options:range: to get an array of all variables in the formula (Profit 2011, Revenue 2011) and then construct an NSDictionary (key = variable name) out of this array by querying my data model.
What do you think?
Is there a better way to do it in your view?
In the formula, how would you replace the variables by their values?
How would you parse the formula?
Thank you!!
Yes, you can do this. This falls under the category of "Using NSPredicate for things for which it was not intended", but will work just fine.
You'll need to replace your variables with a single word that start with a $, since that's how NSPredicate denotes variables:
NSPredicate *p = [NSPredicate predicateWithFormat:#"foo = $bar"];
However you want to do that, great. NSRegularExpression is a fine way to do that.
Once you do that, you'll have something like this:
#"$profitability2011 = $profit2011 / $revenue2011"
You can then pop this through +predicateWithFormat:. You'll get back an NSComparisonPredicate. The -leftExpression will be of type NSVariableExpressionType, and the -rightExpression will be of type NSFunctionExpressionType.
This is where things start to get hairy. If you were to -evaluteWithObject:substitutionVariables:, you'd simply get back a YES or NO value, since a predicate is simply a statement that evaluates to true or false. I haven't explored how you could just evaluate one side (in this case, the -rightExpression), but it's possible that -[NSExpression expressionValueWithObject:context:] might help you. I don't know, because I'm not sure what that "context" parameter is for. It doesn't seem like it's a substitution dictionary, but I could be wrong.
So if that doesn't work (and I have no idea if it will or not), you could use my parser: DDMathParser. It has a parser, similar to NSPredicate's parser, but is specifically tuned for parsing and evaluating mathematical expressions. In your case, you'd do:
#import "DDMathParser.h"
NSString *s = #"$profit2011 / $revenue2011";
NSDictionary *values = ...; // the values of the variables
NSNumber *profitability = [s numberByEvaluatingStringWithSubstitutions:values];
The documentation for DDMathParser is quite extensive, and it can do quite a bit.
edit Dynamic variable resolution
I just pushed a change that allows DDMathParser to resolve functions dynamically. It's important to understand that a function is different from a variable. A function is evaluated, whereas a variable is simply substituted. However, the change only does dynamic resolution for functions, not variables. That's ok, because DDMathParser has this neat thing called argumentless functions.
An argumentless function is a function name that's not followed by an opening parenthesis. For convenience, it's inserted for you. This means that #"pi" is correctly parsed as #"pi()" (since the constant for π is implemented as a function).
In your case, you can do this:
Instead of regexing your string to make variables, simply use the names of the terms:
#"profit_2011 / revenue_2011";
This will be parsed as if you had entered:
#"divide(profit_2011(), revenue_2011())"
You can the set up your DDMathEvaluator object with a function resolver. There are two examples of this in the DDMathParser repository:
This example shows how to use the resolver function to look up the "missing" function in a substitution dictionary (this would be most like what you want)
This example shows you to interpret any missing function as if it evaluated to 42.
Once you implement a resolver function, you can forego having to package all your variables up into a dictionary.
Is there a better way to do it in your view?
Yes - using Flex & Bison.
Possibly you could achieve what you want with a regex - but for many expression grammars, a regex isn't powerful enough to parse the grammar. Also, regex things like this get large, unreadable, and unyieldy.
You can use Flex (a lexer) and Bison (a parser) to create a grammar definition for your expressions, and generate C code (which, as I'm sure you know, works perfectly with Objective-C since Objective-C is C) which you can use to parse your expressions.
In the formula, how would you replace the variables by their values?
As you parse through it with Bison you should have a hash table with variable names and their current values. When you generate the syntax tree, add references to the variables to your syntax tree nodes.
How would you parse the formula?
Again - Flex & Bison are specifically meant to do this kind of thing - and they excel at it.