I've defined a emacs / lisp function within defun dotspacemacs/user-config () like so:
(defun clientdir ()
"docstring"
neotree-dir "~/Projects/Clients"
)
How do I execute it?
That function will evaluate the neotree-dir variable and discard the result, then evaluate the "~/Projects/Clients" string and return it.
i.e. Your function unconditionally returns the value "~/Projects/Clients" (unless neotree-dir is not bound as a variable, in which case it will trigger an error).
I am guessing that you wanted to call a function called neotree-dir and pass it "~/Projects/Clients" as an argument? That would look like this: (neotree-dir "~/Projects/Clients")
If you want to call the function interactively you must declare it as an interactive function:
(defun clientdir ()
"Invoke `neotree-dir' on ~/Projects/Clients"
(interactive)
(neotree-dir "~/Projects/Clients"))
You can then call it with M-x clientdir RET, or bind it to a key sequence, etc...
Related
This question already has an answer here:
Function and Function()
(1 answer)
Closed 5 months ago.
I have a doubt where I'm passing a function as a parameter, for onPressed, like event, I would declare a field like final void Function() onPressed, There are some code where I have seen declarring fields like Function someFunction, I would like to know what is the differnce between using Function and Function(). Thanks,
The main() function came from Java-like languages so it's where all programs started, without it, you can't write any program on Flutter even without UI.
The runApp() function should return a widget that would be attached to the screen as a root of the widget Tree that will be rendered
As we can see in doc, Function is:
part of dart.core;
/// The base class for all function types.
///
/// The run-time type of a function object is subtype of a function type,
/// and as such, a subtype of [Function].
Now, Function(), is literally a function, see the example:
Here you can use this:
final Function() func = () {};
ElevatedButton(
onPressed: func;
)
But you can not:
final Function func = () {};
ElevatedButton(
onPressed: func;
)
Here you get the following error:
The argument type 'Function' can't be assigned to the parameter type 'void Function()?'.dartargument_type_not_assignable
Otherwise, you can use:
Function func() {
return () {};
}
ElevatedButton(
onPressed: func;
)
Use Function somename when you need to return a function from a method.
Use Function() somename when you need to use this, literally, as a function.
As per Flutter docs:
Function is the base class of all the function types. It means it represents all the functions.
Adding parenthesis like: Function() makes it one without any parameter.
To sum up: Function is general and Function() is more specific.
Yep, lets take a look whats is braces actualy means.
The main difference between Method(); and Method, is that in first case, you call a method instant and its all. If you'l try to do var someStuff = Method(), someStuff will get a returning value of Method();
In second case, when you use Method, you actually do not call it, because its a link to a method. Because of it is a link, you cant pass an arguments (which places in braces), and if you try to make set variable like this: var someStuff = Method;, variable someStuff will contains a link to a original Method(), and you can call it in code, and it'l work same.
That means, when you pass a link to a onPressed:, and if link has right signature (in and out param), you haven't write whats goes in method and out, all what you should to do will looks like: onPressed: Method. Dart automatically understand, what params in and out, by comparing theirs signature.
In the same way we can have
nullableClassInstance?.method(blah)
Is there a way to do
nullableFunctionInstance?(blah)
In other words, is there an operator that checks whether a function instance is not null, if so, invoke the function all in one line?
Using the call method, you can achieve what you want with:
nullableFunctionInstance?.call(blah)
There's also the apply method if you want to pass arguments.
If you have a Function Object , you can use the call method and send all the parameters to that which works exactly as calling the function. Here , you can use the null aware member access operator.
void myFun(int a , int b){...}
var myVar = myFun ;
call
The function myVar will only get called if its not null as shown below.
myVar?.call( arg1 , arg2 );
apply
If your function is dynamic or you wish to control which function is being called at run time , you can use the apply static method of Function like so :
Function.apply(myVar , [arg1 , arg2]);
apply takes the function and a List of parameters that will be sent to the function.
Read more about call and apply :
I am new to coffee script. When I am looking at this document https://atom.io/docs/api/v0.198.0/CommandRegistry#instance-add
I see a code segment like,
atom.commands.add 'atom-text-editor',
'user:insert-date': (event) ->
editor = #getModel()
editor.insertText(new Date().toLocaleString())
while the function signature looks,
::add(target, commandName, callback)
So in the code segment, what does : on the second line mean? My understanding is the 'user:insert-date' before : is commandName in the signature. The thing after : is "callback". So : is a argument separator like a ,? I don't find this introduced in the coffee script document http://coffeescript.org
That colon is just part of an object literal. The braces around object literals are optional in CoffeeScript when there's no ambiguity. If we add the optional braces, we get something that looks more like JavaScript:
atom.commands.add 'atom-text-editor', {
'user:insert-date': (event) ->
#...
}
So atom.commands.add is being called with two arguments. The first is the string 'atom-text-editor' and the second is an object with one key ('user:insert-date') whose value is an anonymous function that takes a single argument.
Appending mu is too short's answer (the user is absolutely correct that the second parameter commandNamecan be an object without the explicit braces {})
Atom's sourcecode:
https://github.com/atom/atom/blob/v0.198.0/src/command-registry.coffee#L81
add: (target, commandName, callback) ->
if typeof commandName is 'object'
commands = commandName
disposable = new CompositeDisposable
for commandName, callback of commands
disposable.add #add(target, commandName, callback)
return disposable
Some guy asserts that the following piece of code is an illustration of closure in Lisp. I'm not familiar with Lisp, but believe he is wrong. I don't see any free variables, it seems to me as an example of ordinary high level functions. Could you please judge...
(defun func (callback)
callback()
)
(defun f1() 1)
(defun f1() 2)
func(f1)
func(f2)
No.
There is no function being defined inside func that would enclose local variables inside func. Here is a contrived example based on yours Here is a good example:
Input:
(define f
(lambda (first-word last-word)
(lambda (middle-word)
(string-append first-word middle-word last-word))))
(define f1 (f "The" "cat."))
(define f2 (f "My" "adventure."))
(f1 " black ")
(f1 " sneaky ")
(f2 " dangerous ")
(f2 " dreadful ")
Output:
Welcome to DrScheme, version 4.1.3 [3m].
Language: Pretty Big; memory limit: 128 megabytes.
"The black cat."
"The sneaky cat."
"My dangerous adventure."
"My dreadful adventure."
>
f defines and returns a closure in which the first and last words are enclosed, and which are then reused by calling the newly-created functions f1 and f2.
This post has several hundred views, therefore if non-schemers are reading this, here is the same silly example in python:
def f(first_word, last_word):
""" Function f() returns another function! """
def inner(middle_word):
""" Function inner() is the one that really gets called
later in our examples that produce output text. Function f()
"loads" variables into function inner(). Function inner()
is called a closure because it encloses over variables
defined outside of the scope in which inner() was defined. """
return ' '.join([first_word, middle_word, last_word])
return inner
f1 = f('The', 'cat.')
f2 = f('My', 'adventure.')
f1('black')
Output: 'The black cat.'
f1('sneaky')
Output: 'The sneaky cat.'
f2('dangerous')
Output: 'My dangerous adventure.'
f2('dreadful')
Output: 'My dreadful adventure.'
Here's my contribute as a JavaScript programmer:
A closure is a function that has access to variables defined in its lexical scope (a scope that might not be present anymore when the closure is actually invoked). Here:
function funktionFactory(context) {
// this is the lexical scope of the following anonymous function
return function() {
// do things with context
}
}
Once funktionFactory has returned the lexical scope is gone forever BUT (and it's a big 'but') if the returned function is still referenced (and therefore not garbage collected), then such function (a closure) can still play with the original variable context. Here:
var closure = funktionFactory({
name: "foo"
});
no one but closure can access the name property of the context object (unreachable for any other entity in the software when funktionFactory has returned).
So to answer your question: is func a closure? nope. And callback? neither!
I've been reading through the source code for Moq and I came across the following unit test:
Assert.Throws<ArgumentOutOfRangeException>(() => Times.AtLeast(0));
And for the life of me, I can't remember what () => actually does. I'm think it has something to do with anonymous methods or lambdas. And I'm sure I know what it does, I just can't remember at the moment....
And to make matters worse....google isn't being much help and neither is stackoverflow
Can someone give me a quick answer to a pretty noobish question?
Search StackOverflow for "lambda".
Specifically:
() => Console.WriteLine("Hi!");
That means "a method that takes no arguments and returns void, and when you call it, it writes the message to the console."
You can store it in an Action variable:
Action a = () => Console.WriteLine("Hi!");
And then you can call it:
a();
()=> is a nullary lambda expression. it represents an anonymous function that's passed to assert.Throws, and is called somewhere inside of that function.
void DoThisTwice(Action a) {
a();
a();
}
Action printHello = () => Console.Write("Hello ");
DoThisTwice(printHello);
// prints "Hello Hello "
It's a lambda expression. The most common syntax is using a parameter, so there are no parentheses needed around it:
n => Times.AtLeast(n)
If the number of parameters is something other than one, parentheses are needed:
(n, m) => Times.AtLeast(n + m)
When there are zero parameters, you get the somewhat awkward syntax with the parentheses around the empty parameter list:
() => Times.AtLeast(0)
() => Times.AtLeast(0)
() indicates that the lambda function has no parameters or return value.
=> indicates that a block of code is to follow.
Times.AtLeast(0) calls the Times class's static method AtLeast with a parameter of 0.
That's the definition of a lambda (anonymous) function. Essentially, it's a way to define a function inline, since Assert.Throws takes a function as an argument and attempts to run it (and then verify that it throws a certain exception).
Essentially, the snippet you have there is a unit test that makes sure Times.AtLeast(0) throws a ArgumentOutOfRangeException. The lambda function is necessary (instead of just trying to call the Times.AtLeast function directly from Assert.Throws) in order to pass the proper argument for the test - in this case 0.
MSDN KB article on the topic here: http://msdn.microsoft.com/en-us/library/bb882516.aspx
I don't program in C#, but Googling "C# Lambda" provided this link that answers your question!!!