scala tuple unpacking cannot resolve UPPER argument name? [duplicate] - scala

I have a method in Scala that returns a tuple, let's say the method is called 'test'. Then I want to do
val (X,Y) = test()
However, the pattern-matching only works in Scala when the variable names are lowercase, ie:
val(_X,_Y) = test(); val X = _X; val Y = _Y
... works ok, but is ugly, and not terse. Since X and Y are matrices, I don't really want to have to use lowercase variables. (In scipy and matlab, I wouldn't have such a restriction for example).
I think there is some way to make sure lowercase variables behave like uppercase ones, ie by doing `x`. Perhaps there is some way of making uppercase variables behave like lowercase ones? So, that is my question: is there some way of pattern matching directly into uppercase variables in Scala?

The short answer is don't.
Syntax conventions make your code readable and understandable for others. Scala's convention is that variables start with lower-case and constants and classes start with upper-case. By violating this, not only you get problems like pattern-matching issues, your code becomes less readable. (Believe me, if you ever have to read code written by someone else who didn't care for such conventions, you'll be cursing that person.)
If you want to emphasize that the variables are matrices, I suggest you to use xMatrix and yMatrix or something like that. This will make clear that they're variables and that they represent matrices.
Or create a convention specific to your project that all matrix variables will end with let's say "M", like xM and yM.
It's worth typing a few more characters if it makes your code readable.

There is no way to do this and there shouldn't be. You already have the type of the variable to tell you that it is a matrix, so there is no need to make variable names uppercase.

Related

Julia equivalent of a lisp symbol macro?

I'm trying to do what a Lisp hacker would call a "symbol macro". To wit, here's what I'm using now:
global ghypers = Dict()
macro hyp(variable, value); ghypers[:($variable)] = :($value); end
macro hyp(variable); ghypers[:($variable)]; end
#hyp foo 5
println(ghypers)
println(#hyp foo)
println(#hyp(foo)+1)
So far so good, but the last thing is ugly, I want to do this:
#foo+1
Sort of like this:
macro foo(); ghypers[:foo]; end
println(#foo)
println(#foo()+1)
Close, and works, but not quite what I wanted, which, again, is:
println(#foo+1)
MethodError: no method matching #foo(::LineNumberNode, ::Module, ::Expr)
Except that that doesn't work.
Lisp has the concept of a symbol macro, where you can bind a macro expansion to a symbol, like foo, so that symbol would expand the to value.
Now, an obvious but equally bad (in the unhygienic sense) way to do this would simply be to bind the global var foo to the value, but I don't want global (or, rather, I want them localized in ghypers).
Is there any way to do the thing I'm seeking in Julia?
(<flame> Having been a happy lisp camper for 40+ years, Julia is the first programming language that I can say I actually like even a little. But not having grok'ed the importance of homoiconicity, their macro system is ... well, to my eyes, quite a mess, where Lisp's is clear as rain water. </flame> :-)
There are two direct ways. If the thing is hygienic and referentially transparent, just use a const value. That won't work in your example.
Otherwise you have to use the macro in call syntax: #foo(). There's no around that, it's how Julia syntax work. Although I won't recommend doing it either.
But a nicer alternative, IMHO, would be an "anaphoric context macro", something like:
#withhyper (stuff) begin
println(foo+1)
end
where foo is a name escaped inside some local scope. Expand the block to a variation of
let foo = setup_hyper(stuff, ...)
println(foo+1)
end

How do the Swift REPL and the swiftc compiler interpret the language differently?

Swift has a compiler (swiftc) and a REPL. I like using the REPL to learn and play with language constructs.
In one of my experiments I came across a notable difference w.r.t how "let" works.
The following is, as I would expect, not allowed in swiftc, but the REPL allows it.
let x = 10
let x = 20 // ok in REPL
And now I am wondering what other differences there are. Are they documented anywhere?
In a REPL environment, you'd want to be able to redeclare variables, right? Otherwise, as you keep using the REPL, and you declare more and more variables, let constants, functions, classes, whatever, you'll run out of names to use!
For example, let's say you want to try out string interpolation:
let x = 10
print("x is \(x)!")
And then a while later, you learn about string concatenation, and you want to try that out as well. At this point, you'd want to be able to redeclare a let constant x, right?
let x = "A"
let y = "B"
print(x + y)
You could argue that you could use a or b, but as time goes on, you'll slowly run out of names. REPL is designed like this so that you don't have to restart the REPL very frequently.
So each time you submit something, previously declared symbols that are also declared in the submission will get overwritten. This is documented here.
swiftc has a completely different use case - you usually use it to compile larger programs, with more than just a few lines of code. In these situations, the global scope will have a lot less symbols, and redeclaring variables isn't really practical to implement, because the code execution isn't linear from top to bottom. There could be multiple files as well that talk to each other. How do you figure out what redeclares what? It just doesn't make sense to do this in anywhere other than a REPL.
Other REPLs have this feature too, like csharppad.com for C#, ghci for Haskell, and python, just to name a few. So it's really just a common thing you do when you implement REPLs, not something special to Swift.
In fact, you can reproduce the swiftc behaviour in a REPL by writing the two lines in a function, because now the two lines are in the same submission, and will not overwrite each other.

Subscript multiple characters in Julia variable name?

I can write:
x\_m<TAB> = 5
to get x subscript m as a variable name in Julia. What if I want to subscript a word instead of a single character? This
x\_max<TAB> = 5
doesn't work. However,
x\_m<TAB>\_a<TAB>\_x<TAB> = 5
does work, it's just very uncomfortable. Is there a better way?
As I noted in my comment, not all ASCII characters exist as unicode super- or sub-scripts. In addition, another difficulty in generalizing this tab completion will be determining what \_phi<TAB> should mean: is it ₚₕᵢ or ᵩ? Finally, I'll note that since these characters are cobbled together from different ranges for different uses they look pretty terrible when used together.
A simple hack to support common words you use would be to add them piecemeal to the Base.REPLCompletions.latex_symbols dictionary:
Base.REPLCompletions.latex_symbols["\\_max"] = "ₘₐₓ"
Base.REPLCompletions.latex_symbols["\\_min"] = "ₘᵢₙ"
You can put these additions in your .juliarc.jl file to load them every time on startup. While it may be possible to get a comprehensive solution, it'll take much more work.
Since Julia 1.6 this works for subscripts (\_) and superscripts(\^) in the Julia REPL.
x\_maxTAB will print out like this: xₘₐₓ.
x\^maxTAB will print out like this: xᵐᵃˣ.

Can operators be stored in variables?

This is a thought example of what I am thinking of:
test = 'x > 0';
while str2func(test)
Do your thing
x=x-1;
end
Is it possible to store whole logical operations in a variable like this?
Of course the str2func will break here. If it is possible this function will likely be something else. And I have only added apostrophes to the test variable content, because I cannot think of what else would be the storing method.
I can see it usefull when sending arguments to functions and alike. But mostly I'm just wondering, because I have never seen it done in any programming language before.
You can store the textual representation of a function in a variable and evaluate it, for example
test = 'x > 0';
eval(test)
should result in 1 or 0 depending on x's value.
But you shouldn't use eval for reasons too-often covered here on SO for me to bother repeating. You should instead become familiar with functions and function handles. For example
test = #(x)x>0
makes test a handle to a function which tests whether its argument is greater than 0 or not.
Many languages which are interpreted at run-time, as opposed to compiled languages, have similar capabilities.

Can the C preprocessor perform simple string manipulation?

This is C macro weirdness question.
Is it possible to write a macro that takes string constant X ("...") as argument and evaluates to sting Y of same length such that each character of Y is [constant] arithmetic expression of corresponding character of X.
This is not possible, right ?
No, the C preprocessor considers string literals to be a single token and therefore it cannot perform any such manipulation.
What you are asking for should be done in actual C code. If you are worried about runtime performance and wish to delegate this fixed task at compile time, modern optimising compilers should successfully deal with code like this - they can unroll any loops and pre-compute any fixed expressions, while taking code size and CPU cache use patterns into account, which the preprocessor has no idea about.
On the other hand, you may want your code to include such a modified string literal, but do not want or need the original - e.g. you want to have obfuscated text that your program will decode and you do not want to have the original strings in your executable. In that case, you can use some build-system scripting to do that by, for example, using another C program to produce the modified strings and defining them as macros in the C compiler command line for your actual program.
As already said by others, the preprocessor sees entire strings as tokens. There is only one exception the _Pragma operator, that takes a string as argument and tokenizes its contents to pass it to a #pragma directive.
So unless your targeting a _Pragma the only way to do things in the preprocessing phases is to have them written as token sequences, manipulate them and to stringify them at the end.