Variable evaluation in LateX - variables

I have the following piece of latex code:
\def\a{1}
\def\b{2}
\def\c{\a+\b}
\def\d{\c/2}
I expected \d to have the value 1.5. But it did not. However, adding parenthesis to the definition of \c like
\def\c{\a+\b}
Doesn't work either, because if I use \c somewhere, it complains about the parenthesis. Is there a way to evaluate \c before dividing it by 2 in the definition of \d? Like:
\def\d{\eval{\c}/2}
(I made that \eval up to show what I mean)

You could use the calc package for arithmetic operations. The package fp works with real numbers.
For discussing LaTeX problems you're kindly invited to visit tex.stackexchange.com.

You need to remember that \def is about creating replacement text. It will always give you back what you put in, quite apart from not knowing anything about maths. If we assume you are using e-TeX (likely), then for integer expressions you might do
\def\a{1}
\def\b{2}
\edef\c{\number\intexpr \a + \b \relax}
\edef\d{\number\intexpr \c / 2 \relax}
This uses the e-TeX primitive \intexpr, which does integer mathematics. For real numbers, Stefan is right that the fp package is the best approach.

Related

How to add a small bit of context in a grammar?

I am tasked to parse (and transform) a code of a computer language, that has a slight quirk in its rules, at least I see it this way. To be exact, the compiler treats new lines (as well as semicolons) as statement separators, but other than that (e.g. inside the statement) it treats them as spacers (whitespace).
As an example, this code:
try
local x = 5 / 0
catch (i)
print(i + "\n")
is proved to be equivalent to this:
try local x = 5 / 0 catch (i) print(i + "\n")
I don't see how I can express such a rule in EBNF, or specifically in Lark EBNF dialect. I mean in a sensible way. I probably could define all possible newline positions inside all statements, but it would be cumbersome and error-prone.
I wish to find a way to treat newlines contextually. Is there a proven method for this, preferably within Python/Lark domain? If I have to modify the parser for that purpose, then where should I start?
Or if I misunderstood something in this language in particular or in machine language parsing in general, or my statement of the problem is wrong, I'd also be happy to get educated.
(As you may guess, the language in question has a well proven implementation, but no officially defined grammar. Also, it is Squirrel, for all that it matters.)
The relevant quote from the "specification" is this:
A squirrel program is a simple sequence of statements.:
stats := stat [';'|'\n'] stats
[...] Statements can be separated with a new line or ‘;’ (or with the keywords case or default if inside a switch/case statement), both symbols are not required if the statement is followed by ‘}’.
These are relatively complex rules and in their totality not context free if newlines can also be ignored everywhere else. Note however that in my understanding the text implies that ; or \n are required when no of the other cases apply. That would make your example illegal. That probably means that the BNF as written is correct, e.g. both ; and \n are optionally everywhere. In that case you can (for lark) just put an %ignore "\n" statement and it should work fine.
Also, lark should not complain if you both ignore the \n and use it in a rule: Where useful it will match it in a rule, otherwise it will just ignore it. Note however that this breaks if you use a Terminal that includes the \n (e.g. WS or /\s/). Just have \n as an extra case.
(For the future: You will probably get faster response for lark questions if you ask over on gitter or at least put a link to SO there.)

What is Nim's approach to distinguish between commands?

I'm trying to understand what kind of approach is used by Nim to distinguish between commands.
There's the "separatist approach" where a semicolon just separates commands (used in Pascal for example), the "terminist approach" where a semicolon completely terminates the command (used in C, C++, Java, etc.) and the "liberal approach" where the programmer can decide whether or not to use a semicolon.
My thoughts are that Nim belongs to the liberal approach, but that would mean that semicolons could be added at the end of commands and Nim doesn't support that.
Any other thoughts?
I'm trying to understand what kind of approach is used by Nim to
distinguish between commands.
Why? This doesn't help in any way ... Nim has a complex syntax that doesn't readily fit into such boxes.
Your question is confused in several ways. First, what is a "command"? Semicolons separate statements or expressions. The difference between your categories matter mostly in expression languages--it determines whether the value of a block ending with a semicolon is the bottom value, or the value of the previous expression. "separatist" languages are confusing, error-prone, bad design, and obsolete--the mistakes of Algol are ancient history. Second, the categories don't make a lot of sense in languages like Nim where end-of-line is syntactically significant--a "missing" semicolon before a newline isn't really missing because the newline serves the same function. Thirdly, Nim most certainly does allow semicolons at the ends of expressions or statements (but it doesn't allow empty statements or expressions, so ;; is disallowed).
Consider:
proc a: int = 5 # returns 5
proc b: int = 5; # syntax error
proc c: int = # returns 5
5
proc d: int = # returns 5
5;
proc e: int = # syntax error
5;;
Since the ; that differentiates c and d makes no semantic difference, one could say that it's closer to "liberal" than to "separatist" or "terminist", but it isn't very liberal ... you can't just put semicolons anywhere.
Nim, like Python, is a whitespace-aware language. It uses newlines as statement separators and indentation to produce block structures.
Not all languages have visible statement separators, although some allow a visible statement separator in some circumstances. (For example, in Python simple statements can be separated by semicolons, but not compound statements.)
"There are more things in heaven and earth, Horatio, Than are dreamt of in your philosophy" (Hamlet I.5:159–167)

What's the difference between parenthesis $() and curly bracket ${} syntax in Makefile?

Is there any differences in invoking variables with syntax ${var} and $(var)? For instance, in the way the variable will be expanded or anything?
There's no difference – they mean exactly the same (in GNU Make and in POSIX make).
I think that $(round brackets) look tidier, but that's just personal preference.
(Other answers point to the relevant sections of the GNU Make documentation, and note that you shouldn't mix the syntaxes within a single expression)
The Basics of Variable References section from the GNU make documentation state no differences:
To substitute a variable's value, write a dollar sign followed by the
name of the variable in parentheses or braces: either $(foo) or
${foo} is a valid reference to the variable foo.
As already correctly pointed out, there is no difference but be be wary not to mix the two kind of delimiters as it can lead to cryptic errors like in the GNU make example by unomadh.
From the GNU make manual on the Function Call Syntax (emphasis mine):
[…] If the arguments themselves contain other function calls or variable references, it is wisest to use the same kind of delimiters for all the references; write $(subst a,b,$(x)), not $(subst a,b,${x}). This is because it is clearer, and because only one type of delimiter is matched to find the end of the reference.
The ${} style lets you test the make rules in the shell, if you have the corresponding environment variables set, since that is compatible with bash.
Actually, it seems to be fairly different:
, = ,
list = a,b,c
$(info $(subst $(,),-,$(list))_EOL)
$(info $(subst ${,},-,$(list))_EOL)
outputs
a-b-c_EOL
md/init-profile.md:4: *** unterminated variable reference. Stop.
But so far I only found this difference when the variable name into ${...} contains itself a comma. I first thought ${...} was expanding the comma not as part as the value, but it turns out i'm not able to hack it this way. I still don't understand this... If anyone had an explanation, I'd be happy to know !
It makes a difference if the expression contains unbalanced brackets:
${info ${subst ),(,:-)}}
$(info $(subst ),(,:-)))
->
:-(
*** insufficient number of arguments (1) to function 'subst'. Stop.
For variable references, this makes a difference for functions, or for variable names that contain brackets (bad idea)

ANSI escape codes in GNU Smalltalk

I'm trying to make a console-based program that makes use of ANSI escape codes with GNU Smalltalk. I can't seem to figure out how to go about printing a string object formatted with ANSI escape codes. I've tried the following.
'\x1b[31mHi' displayNl
This prints the entire string, including the escape code, without any formatting. I would have expected this to print "Hi" in red (and then everything else in the console after that, as I didn't reset the color.)
After googling a bit, I was able to find a couple issues on mailing lists where people were trying to produce things like newlines using "\n". Most of the answers were using the Transcript object's cr method, but I didn't find anything about colors in the textCollector class.
It looks like it shouldn't be all that hard to create my own module in C to achieve this functionality, but I'd like to know if there's a better way first.
I'm aware of the ncurses bindings, but I'm not sure that'd be practical for just making certain pieces of text in the program colored. So, is there a standard way of outputting colored text to the terminal in GNU Smalltalk using ANSI escape sequences?
Ended up getting an answer on the GNU Smalltalk mailing list. Looks like you can use an interpolation operator to achieve this.
For example ('%1[31mHi' % #($<16r1B>)) displayNl. would change the color to red, and ('%1[34mHi' % #($<16r1B>)) displayNl. would change the color to blue.
Basically, the % operator looks for a sequences that look like "%(number)" and replaces them with the objects in the array to the right of the operator. In our case, the array has one item, which is the ascii escape character in hexadecimal. So the "%1" in "%1[31mHi' is being replaced with the escape character, and then printed.
(This answer was stolen almost verbatim from Paolo on the GNU Smalltalk mailing list.)

How to split lines in Haskell?

I have made a program which takes a 1000 digit number as input.
It is fixed, so I put this input into the code file itself.
I would obviously be storing it as Integer type, but how do I do it?
I have tried the program by having 1000 digits in the same line. I know this is the worst possible code format! But it works.
How can assign the variable this number, and split its lines. I read somewhere something about eos? Ruby, end of what?
I was thinking that something similar to comments could be used here.
Help will be appreciated.
the basic idea is to make this work:
a=3847981438917489137897491412341234
983745893289572395725258923745897232
instead of something like this:
a=3847981438917489137897491412341234983745893289572395725258923745897232
Haskell doesn't have a way to split (non-String) literals across multiple lines. Since Strings are an exception, we can shoehorn in other literals by parsing a multiline String:
v = read
"32456\
\23857\
\23545" :: Integer
Alternately, you can use list syntax if you think it's prettier:
v = read . concat $
["32456"
,"24357"
,"23476"
] :: Integer
The price you pay for this is that some work will be done (once) at runtime, namely, the parsing (e.g. read).