I am reading this post about time.startTimer declaration and definition.
From the answer, time.startTimer is declared in src/time/sleep.go
as follows:
func startTimer(*runtimeTimer)
And its definition is in src/runtime/time.go as follows:
func startTimer(t *timer) {
if raceenabled {
racerelease(unsafe.Pointer(t))
}
addtimer(t)
}
So it seems that you can declare a function in one .go file and implement it in another .go file. I tried the same way, for example, declare a function in a.go and implement it in b.go, but it always failed when go run a.go. Is that the correct way to do so? How can I declare a function that is implemented in another .go file? There is no import in either sleep.go or time.go. How does Go do it?
Thanks
If you look on the line above the startTimer body, you will see a special directive for the go compiler:
//go:linkname stopTimer time.stopTimer
From the compile command documentation
//go:linkname localname importpath.name
The //go:linkname directive instructs the compiler to use “importpath.name” as the object file symbol name for the variable or function declared as “localname” in the source code. Because this directive can subvert the type system and package modularity, it is only enabled in files that have imported "unsafe".
Related
If I run this code in the Swift playground it works fine. The function is defined before it is called.
import Cocoa
func addValues(valueA:Double, valueB:Double)
{
let result = valueB + valueB
println("Result \(result)")
}
addValues(23.83, 87.12)
If I try to call the function before it is defined I get an error message. Not unexpected because the function is still unknown to the compiler. (For some reason it still seems to work)
import Cocoa
addValues(23.83, 87.12)
func addValues(valueA:Double, valueB:Double)
{
let result = valueB + valueB
println("Result \(result)")
}
In Objective-C I was able to declare the function head only on top of the file and define the function later at the end of the code. So the second version of my sample would work too.
Can I do this in Swift too?
I found nothing in the documentations.
EDIT:
andyvn22 wrote this will only happen in the playground and not in actual projects so I tried it.
Just a simple command line tool with a function. I get the same error and it will not compile. If I move the call after the function definition it works fine.
I believe that in Swift you generally cannot call functions before they have been declared, as they are unknown to the compiler at that time. In Objective C this was different because declaring the function in the header introduced it to the compiler at import time as a pointer to the function definition. Then, when the function was called the compiler could reference the imported pointer which would then take it to the function definition in the file. In Swift, this is different because we are not required to declare our properties in a header file - we simultaneously declare and define in one file. While simpler, this creates a problem resembling yours, where the compiler is unaware of the function until its declaration/definition. In classes, the rules are changed because we can call functions like this:
class HypnosisViewController: UIViewController {
override func viewDidLoad() {
// Function call
addValues(30.0, 40.0)
}
// Function declaration
func addValues(valueA:Double, valueB:Double){
let result = valueB + valueB
println("Result \(result)")
}
}
even though the function isn't declared until after the function call. We can do this because when an instance of a class is created, all of the instance variables and methods of that class are initialized to that object. This means the compiler has already initialized - and therefore recognized - the addValues function, so it doesn't complain. However, when code is executed linearly, such as in Playground, we do not have this initialization so it is not possible to call a function before it's declaration for the reasons previously stated (the compiler is unaware of the function). Playground's atypical behavior with this kind of situation is a little more ambiguous to me, because it complains about the function call preceding the function declaration however it still shows the result of the call to the right. I believe this is due to the unique way that Playground compiles its code. I apologize because I am unaware of a technique to retain this Objective C functionality in Swift, which I know was part of your question. However I hope this gave you some background as to why this is happening.
I have been searching an entire afternoon and have found no solution to call in matlab a function by specifying its path and not adding its directory to the path.
This question is quite similar to Is it possible to call a function that is not in the path in MATLAB?, but in my case, I do not want to call a built-in function, but just a normal function as defined in an m-file.
I think handles might be a solution (because apparently they can refer to functions not on the path), but I again found no way to create a handle without cd-ing to the directory, creating it there and the cd-ing back. Trying to 'explore' what a function handle object is and how to make one with a reference to a specific function not on the path has led me nowhere.
So the solution might come from two angles:
1) You know how to create a handle for an m-file in a specific directory.
2) You know a way to call a function not on the matlab path.
EDIT: I have just discovered the function functions(myhandle) which actually lets you see the filepath to which the handle is referring. But still no way to modify it though...
This is doable, but requires a bit of parsing, and a call to evalin.
I added (many years ago!) a function to the MATLAB Central File Exchange called externalFcn
http://www.mathworks.com/matlabcentral/fileexchange/4361-externalfcn
that manages calls to off-path functions. For instance, I have a function called offpathFcn that simply returns a structure with a success message, and the value of an input. Storing that function off my MATLAB path, I can call it using:
externalfcn('out = C:\MFILES_OffPath\offpathFcn(''this is a test'')');
This returns:
out =
success: 1
input: 'this is a test'
(Note that my implementation is limited, and improvable; you have to include an output with an equal sign for this to work. But it should show you how to achieve what you want.)
(MathWorks application engineer)
The solution as noted in the comment 1 to create a function handle before calling the function is nicely implemented by #Rody Oldenhuis' FEX Contribution:
http://www.mathworks.com/matlabcentral/fileexchange/45941-constructor-for-functionhandles
function [varargout]=funeval(fun,varargin)
% INPUT:
% fun: (char) full path to function file
curdir=cd;
[fundir,funname]=fileparts(fun);
cd(fundir);
[varargout{1:nargout}] =feval(funname,varargin{:})
cd(curdir);
I've modified Thierry Dalon's code to avoid the use of feval, which I always feel uncomfortable with. Note this still doesn't get around cd-ing to the directory in question, but well, it happens behind the scenes, so pretend it doesn't happen :-)
Also note what Ben Voigt pointed out above: calls to helper functions off the path will fail.
function [varargout]=funeval(FunctionHandle, FunctionPath, varargin)
% INPUT:
% FunctionHandle: handle to the function to be called; eg #MyFunction
% FunctionPath: the path to that function
% varargin: the arguments to be passed to Myfunction
curdir=cd;
cd(FunctionPath)
[varargout{1:nargout}] = FunctionHandle(varargin{:});
cd(curdir);
end
and calling it would look like
Output = funeval(#MyFunction, 'c:\SomeDirOffMatlabsPath\', InputArgToMyFunc)
The run command can run a script file from any directory, but it can't call a function (with input and output arguments).
Neither feval nor str2func permit directory information in the function string.
I suggest writing your own wrapper for str2func that:
saves the working directory
changes directory to the script directory
creates a function handle
restores the original working directory
Beware, however, that a handle to a function not in the path is likely to break, because the function will be unable to invoke any helper code stored in other files in its directory.
Is there a way to have a function in Lua that can be accessed from any module in a project without having to first require it?
something like:
module(..., package.seeall);
function globFoo()
print('global foo called');
end
and have it called from somwhere else, like main
--main
globFoo();
without requiring it?
A module is just a Lua script. You can do whatever you want there; you don't even have to call module in your module script. Indeed, module is generally considered harmful these days, which is why it was deprecated in Lua 5.2.
Really, it's a matter of simply moving your code around:
function globFoo()
print('global foo called');
end
module(..., package.seeall); --Module created after global function
So yes, you can have a module modify the global table. I would very much suggest that you don't (because it creates implicit ordering between Lua scripts, which makes it hard to know which script uses which stuff). But you can do it.
A sample of how this is done :
in global.lua (where the global function is located) :
globalFunction1 = function(params)
print("I am globalFunction1")
end
In the calling file, caller.lua :
globalFunction1(params) -- This will call the global function above
I had an old ipy_user_conf.py in which I included a simple function into the user namespace like this:
import IPython.ipapi
ip = IPython.ipapi.get()
def myfunc():
...
ip.user_ns['myfunc'] = myfunc
Then, I could use myfunc in the prompt.
However, I updated to IPython 0.12.1 and now the ip_user_conf.py does not work. I haven't seen how to translate such a custom function for prompts to the new configuration model.
Which is the way to do this?
Best regards,
Manuel.
UPDATE: Changed the subject to question
After reading a bit of the documentation (and peeking at the source code for leads) I found the solution for this problem.
Simply now you should move all your custom functions to a module inside your .ipython directory. Since what I was doing was a simple function that returns the git branch and status for the current directory, I created a file called gitprompt.py and then I included the filename in the exec_file configuration option:
c.InteractiveShellApp.exec_files = [b'gitprompt.py']
All definitions in such files are placed into the user namespace. So now I can use it inside my prompt:
# Input prompt. '\#' will be transformed to the prompt number
c.PromptManager.in_template = br'{color.Green}\# {color.LightBlue}~\u{color.Green}:\w{color.LightBlue} {git_branch_and_st} \$\n>>> '
# Continuation prompt.
c.PromptManager.in2_template = br'... '
Notice that in order for the function to behave as such (i.e called each time the prompt is printed) you need to use the IPython.core.prompts.LazyEvaluation class. You may use it as a decorator for your function. The gitprompt.py has being placed in the public domain as the gist: https://gist.github.com/2719419
I am trying to make a small interpreter using Flex and Bison.
Now I have two files: parser.l and parser.y. Usually, main function is put in parser.y file. What I want to do is to put the main function in a different file main.cpp which makes my package look neat.
#include "y.tab.h"
int main()
{
yyparse();
return 0;
}
But when I compile, I got an error:
undefined reference to `main'
So I know there is something wrong to include y.tab.h.
Could you someone to tell me how to do it?
Solution
I just figured it out:
add the following to your main.c file:
extern FILE *yyin;
extern FILE *yyout;
extern int yyparse(void);
SO noted:
I just figured it out: add the following to your main.c file:
extern FILE *yyin;
extern FILE *yyout;
extern int yyparse(void);
#Jonathan Leffler Noted
You don't really need yyin or yyout since you don't (yet) reference
them from the file containing main(). However, if you end up doing
work such as reading from files specified on the command line instead
of standard input, you may need them. It would be nice if Bison
generated a header with the appropriate declarations in it. The
y.tab.h file is not, however, the place for that information; it is
used to convey information between the parser and the lexical
analyzer, not between the application and the parser.