I assigned to a project written by someone else. They passed parameters as variables (I mean those things copied to stack when a method is called) and I like them to converted to pointers. It runs significantly faster because only 32-bit or 64-bit pointers are passed to the subroutines. I have almost 600 methods to be converted.
An example method is defined as:
bool insideWindow(tsPoint Point, tsWindow Window)
When I change the type tsWindow into psWindow (defined as *tsWindow) I need to change all dots (.) to (->) in order to imply a pointer operation.
Is there any easy way to change these in QtCreator? To put in another way, I want to change the type to a pointer type and QtCreator will easily change dots into -> ?
Thanks
Well, it is easily solved by passing variables as references. All I need to do is to modify the function prototype (both in h and in cpp files).
bool insideWindow(tsPoint &Point, tsWindow &Window)
This way it still needs a dot (means I won't change the code, replacing dots with -> operators) and they are passed as pointers in fact.
http://www.cprogramming.com/tutorial/references.html
Related
I am new to Julia. Have a quick question.
In Fortran, we can do
implicit none
Therefore whenever we use a variable, we need to define it first. Otherwise it will give error.
In Julia, I want to do the same time thing. I want to define the type of each variable first, like Float64, Int64, etc. So that I wish that Julia no longer need to automatically do type conversion, which may slow down the code.
Because I know if Julia code looks like Fortran it usually runs fast.
So, in short, is there a way in Julia such that, I can force it to only use variables whose types has been defined, and otherwise give me an error message? I just want to be strict.
I just wanted to define all the variables first, then use them. Just like Fortran does.
Thanks!
[Edit]
As suggested by the experts who answers the questions, thank you very much! I know that perhaps in Julia there is no need to manually define each variables one by one. Because for one thing, if I do that, the code will become just like Fortran, and it can be very very long especially if I have many variables.
But if I do not define the type of the each variables, is Julia smart enough to know the type? Will it do some conversions which may slow down the code?
Also, even if there is no need to define variables one by one, is there in some situations we may have to manually define the type manually?
No, this is not possible* as such. You can, however, add type annotations at any point in your code, which will raise an error if the variable is not of the expected type:
julia> i = 1
1
julia> i::Int64
1
julia> i = 1.0
1.0
julia> i::Int64
ERROR: TypeError: in typeassert, expected Int64, got a value of type Float64
Stacktrace:
[1] top-level scope
# REPL[4]:1
julia> i=0x01::UInt8
0x01
*Julia is a dynamically-typed language, though there are packages such as https://github.com/aviatesk/JET.jl for static type-checking (i.e., no type annotations required) and https://github.com/JuliaDebug/Cthulhu.jl for exploring Julia's type inference system.
Strict type declaration is not how you achieve performance in Julia.
You achieve the performance by type stability.
Moreover declaring the types is usually not recommended because it decreases interoperability.
Consider the following function:
f(x::Int) = rand() < 4+x ? 1 : "0"
The types of everything seem to be known. However, this is a terrible (from performance point of view) function because the type of output can not be calcuated by looking types of input. And this is exactly how you write the performant code with regard to types.
So how to check your code? There is a special macro #code_warntype to detect such cases so you can correct your code:
Another type related issue are the containers that should not be specified by abstract elements. So you never want to have neither Vector{Any} nor Vector{Real} - rather than that you want Vector{Int} or Vector{Float64}.
See also https://docs.julialang.org/en/v1/manual/performance-tips/ for further discussion.
I'm currently programming on Julia via command line session.
I know that the predefined functions in Julia (e.g. sqrt) can take on a variable value but in a particular session I tried to use the function as sqrt(25) and it gave me 5.0 but in the same session when I wrote sqrt=9, then it says
"Error: cannot assign variable Base.sqrt from module Main"
and if I have to make this happen I have to open a new session all over again and assign a variable value to sqrt sqrt=9and when I do so then again it says
ERROR:MethodError: objects of type Int64 are not callable
when I try to use sqrt as a function.
The same thing happens with pi.
The topic you are asking about is a bit tricky. Although I agree with the general recommendation of PilouPili it is sometimes not that obvious.
Your question can be decomposed into two issues:
ERROR:MethodError: objects of type Int64 are not callable
This one is pretty clear, I guess, and should be expected if you have some experience in other programming languages. The situation is that name sqrt in the current scope is bound to value 9 and objects of type Int64 are not callable.
The other error
"Error: cannot assign variable Base.sqrt from module Main"
is more complex and may be non obvious. You are free to use name sqrt for your own variables in your current scope until you call or reference the sqrt function. Only after such operations the binding to sqrt is resolved in the current scope (only recently some corner case bugs related to when bindings are resolved were fixed https://github.com/JuliaLang/julia/issues/30234). From this moment you are not allowed to change the value of sqrt because Julia disallows assigning values to variables imported from other modules.
The relevant passages from the Julia manual are (https://docs.julialang.org/en/latest/manual/modules/):
The statement using Lib means that a module called Lib will be available for resolving names as needed. When a global variable is encountered that has no definition in the current module, the system will search for it among variables exported by Lib and import it if it is found there. This means that all uses of that global within the current module will resolve to the definition of that variable in Lib.
and
Once a variable is made visible via using or import, a module may not create its own variable with the same name. Imported variables are read-only; assigning to a global variable always affects a variable owned by the current module, or else raises an error.
To better understand what these rules mean I think it is best to illustrate them with an example:
julia> module A
export x, y
x = 10
y = 100
end
Main.A
julia> using .A
julia> x = 1000
1000
julia> y
100
julia> y = 1000
ERROR: cannot assign variable A.y from module Main
on the other hand by calling import explicitly instead of using you resolve the binding immediately:
julia> module A
export x, y
x = 10
y = 100
end
Main.A
julia> import .A: x, y
julia> x = 1000
ERROR: cannot assign variable A.x from module Main
And you can see that it is not something specific to Base or functions but any module and any variable. And this is actually the case when you might encounter this problem in practice, as it is rather obvious that sqrt is a predefined function, but something like SOME_CONSTANT might or might not be defined and exported by the modules you call using on and the behavior of Julia code will differ in cases when you first assign to SOME_CONSTANT in global scope and when you first read SOME_CONSTANT.
Finally, there is a special case when you want to add methods to functions defined in the other module - which is allowed or not depending on how you introduce the name in the current scope, you can read about the details here what are the rules in this case.
Bogumił's answer is good and accurate, but I think it can be described a bit more succinctly.
Julia — like most programming languages — allows you to define your own variables with the same name as things that are built-in (or more generally, provided by using a package). This is a great thing, because otherwise you'd have to tip-toe around the many hundreds of names that Julia and its packages provide.
There are two catches, though:
Once you've used a built-in name or a name from any package, you can no longer define your own variables with the same name (in the same scope). That's the Error: cannot assign variable Base.sqrt from module Main: you've already used sqrt(4) and now are trying to define sqrt=2. The workaround? Just use a different name for your variable.
You can define your own variable with the same name as a built-in name or a name from any package if you've not used it yet, but then it takes on the definition you've given it. That's what's happening with ERROR: MethodError: objects of type Int64 are not callable: you've defined something like sqrt=2 and then tried to use sqrt(4). The workaround? You can still reference the other definition by qualifying it with its module name. In this case sqrt is provided by Base, so you can still call Base.sqrt. You can even re-assign sqrt = Base.sqrt to restore its original definition.
In this manner, the names provided by Base and other packages you're using are a bit like Schrödinger's cat: they're in this kinda-there-but-not-really state until you do something with them. If you look at them first, then they exist, but if you define your own variable first, then they don't.
In a sense, any imperative code can be converted to pure functional form by making every operation receive and pass on a 'state of the world' parameter.
However, suppose you have some code that is almost in pure functional form except that, buried many layers of function calls deep, are a handful of imperative operations that modify global or at least widely accessed state e.g. calling a random number generator, updating a counter, printing some debug info, and you want to convert it to pure functional form, algorithmically, with the minimum of changes.
Is there a way to do this without essentially turning the entire program inside out?
This isn't technically all that hard.
If all you want to do is avoid modifying global state, e.g, make the code re-entrant, then for any side-effecting function F that reads X, writes global variable Y,
and returns Z, transform it into F' that reads X, modifies a struct containing Y passed to it, and returns Z. If A calls B calls .. transitively calls F,
and F modifies global Y, then A' must build a reference to a struct containing Y and pass it to B. Now all your functions only modify values passed to them; they have no side effect on global state. (Well, we can argue about what A' does).
[Somebody may complain that (File/Screen/Device) Output done by F can't be handled. Well, either you want the immediate side effect on the world or you don't. If you don't, add the "state" of the Output as Y, and modify that; A' can return the desired Output as a result.]
If you insist on making the the program functional then any side effect of F on global Y has be changed to pass Y in, copying Y while changing it to produce Y', and then F' must return a pair . Callers of F must pass in Y, and use the resulting Y' in all code reachable from the call site.
The bit about copying gets you into real trouble: where is the logic to do a deep copy of Y to be found? If you find it, you may discover that deep copy produces an enormous structure and your storage demand gets impossible quickly. Now you need to find a way to make Y' share the parts of Y that haven't changed.
Now, if you want to do either of these tasks on a big code, you probably don't want to do it by hand; people are bad at handling this kind of detail and they want to cheat/rewrite/... If you really want to do this, you want a source-to-source program transformation system, which can mechanically apply the necessary steps.
I'll note that standard compilation techniques convert programs to so called "static single assignment (SSA)" form, which converts as much of the program, represented in the IR, into a functional program because it is easier to transform/optimize. They still worry about global storage.
This is similar to my previous question, but a bit more complicated.
Before I was defining a type with an associated integer as a parameter, Intp{p}. Now I would like to define a type using a vector as a parameter.
The following is the closest I can write to what I want:
type Extp{g::Vector{T}}
c::Vector{T}
end
In other words, Extp should be defined with respect to a Vector, g, and I want the contents, c, to be another Vector, whose entries should be the of the same type as the entries of g.
Well, this does not work.
Problem 1: I don't think I can use :: in the type parameter.
Problem 2: I could work around that by making the types of g and c arbitary and just making sure the types in the vectors match up in the constructor. But, even if I completely take everything out and use
type Extp{g}
c
end
it still doesn't seem to like this. When I try to use it the way I want to,
julia> Extp{[1,1,1]}([0,0,1])
ERROR: type: apply_type: in Extp, expected Type{T<:Top}, got Array{Int64,1}
So, does Julia just not like particular Vectors being associated with types? Does what I'm trying to do only work with integers, like in my Intp question?
EDIT: In the documentation I see that type parameters "can be any type at all (or an integer, actually, although here it’s clearly used as a type)." Does that mean that what I'm asking is impossible, and that that only types and integers work for Type parameters? If so, why? (what makes integers special over other types in Julia in this way?)
In Julia 0.4, you can use any "bitstype" as a parameter of a type. However, a vector is not a bitstype, so this is not going to work. The closest analog is to use a tuple: for example, (3.2, 1.5) is a perfectly valid type parameter.
In a sense vectors (or any mutable object) are antithetical to types, which cannot change at runtime.
Here is the relevant quote:
Both abstract and concrete types can be parameterized by other types
and by certain other values (currently integers, symbols, bools, and
tuples thereof).
So, your EDIT is correct. Widening this has come up on the Julia issues page (e.g., #5102 and #6081 were two related issues I found with some discussion), so this may change in the future - I'm guessing not in v0.4 though. It'd have to be an immutable type really to make any sense, so not Vector. I'm not sure I understand your application, but would a Tuple work?
I've written an experimental function evaluator that allows me to bind simple functions together such that when the variables change, all functions that rely on those variables (and the functions that rely on those functions, etc.) are updated simultaneously. The way I do this is instead of evaluating the function immediately as it's entered in, I store the function. Only when an output value is requested to I evaluate the function, and I evaluate it each and every time an output value is requested.
For example:
pi = 3.14159
rad = 5
area = pi * rad * rad
perim = 2 * pi * rad
I define 'pi' and 'rad' as variables (well, functions that return a constant), and 'area' and 'perim' as functions. Any time either 'pi' or 'rad' change, I expect the results of 'area' and 'perim' to change in kind. Likewise, if there were any functions depending on 'area' or 'perim', the results of those would change as well.
This is all working as expected. The problem here is when the user introduces recursion - either accidental or intentional. There is no logic in my grammar - it's simply an evaluator - so I can't provide the user with a way to 'break out' of recursion. I'd like to prevent it from happening at all, which means I need a way to detect it and declare the offending input as invalid.
For example:
a = b
b = c
c = a
Right now evaluating the last line results in a StackOverflowException (while the first two lines evaluate to '0' - an undeclared variable/function is equal to 0). What I would like to do is detect the circular logic situation and forbid the user from inputing such a statement. I want to do this regardless of how deep the circular logic is hidden, but I have no idea how to go about doing so.
Behind the scenes, by the way, input strings are converted to tokens via a simple scanner, then to an abstract syntax tree via a hand-written recursive descent parser, then the AST is evaluated. The language is C#, but I'm not looking for a code solution - logic alone will be fine.
Note: this is a personal project I'm using to learn about how parsers and compilers work, so it's not mission critical - however the knowledge I take away from this I do plan to put to work in real life at some point. Any help you guys can provide would be appreciated greatly. =)
Edit: In case anyone's curious, this post on my blog describes why I'm trying to learn this, and what I'm getting out of it.
I've had a similar problem to this in the past.
My solution was to push variable names onto a stack as I recursed through the expressions to check syntax, and pop them as I exited a recursion level.
Before I pushed each variable name onto the stack, I would check if it was already there.
If it was, then this was a circular reference.
I was even able to display the names of the variables in the circular reference chain (as they would be on the stack and could be popped off in sequence until I reached the offending name).
EDIT: Of course, this was for single formulae... For your problem, a cyclic graph of variable assignments would be the better way to go.
A solution (probably not the best) is to create a dependency graph.
Each time a function is added or changed, the dependency graph is checked for cylces.
This can be cut short. Each time a function is added, or changed, flag it. If the evaluation results in a call to the function that is flagged, you have a cycle.
Example:
a = b
flag a
eval b (not found)
unflag a
b = c
flag b
eval c (not found)
unflag b
c = a
flag c
eval a
eval b
eval c (flagged) -> Cycle, discard change to c!
unflag c
In reply to the comment on answer two:
(Sorry, just messed up my openid creation so I'll have to get the old stuff linked later...)
If you switch "flag" for "push" and "unflag" for "pop", it's pretty much the same thing :)
The only advantage of using the stack is the ease of which you can provide detailed information on the cycle, no matter what the depth. (Useful for error messages :) )
Andrew