An objects property can be a simple property or a function. Is there some easier way in CoffeeScript to get the value of this property?
value = if typeof obj.property is "function" then obj.property() else obj.property
I don't know if it is idiomatic but you could use (abuse?) the existential operator for this purpose.
When you say this:
obj.p?()
# ---^
CoffeeScript will convert that to:
typeof obj.p === "function" ? obj.p() : void 0
so if p is a function, it will be called, otherwise you get undefined. Then you can toss in another existential operator to fall back to obj.p if obj.p?() is undefined:
obj.p?() ? obj.p
There is a whole in this though, if you have:
obj =
u: -> undefined
then obj.u?() ? obj.u will give you the whole function back rather than the undefined that the function returns. If you have to face that possibility then I think you're stuck writing your own function:
prop = (x) ->
# Argument handling and preserving `#` is left as an exercise
if typeof x == 'function'
x()
else
x
and saying x = prop obj.maybe_function_maybe_not.
Demo: http://jsfiddle.net/ambiguous/hyv6pdtc/
If you happen to have Underscore around, you could use it's result function:
result _.result(object, property)
If the value of the named property is a function then invoke it with the object as context; otherwise, return it.
Related
I'm working on a MATLAB app that programatically creates anonymous functions to evaluate any native MATLAB function and pass it a list of variables as argument. In the example below, 'formula' contains a string with the function and arguments to be evaluated (e.g., "sum( var1, var2 )" ). The formulas sometimes contain function calls nested within function calls, so the code below would be used recursively until obtaining the final result:
Func2 = str2func( sprintf( '#(%s) %s', strjoin( varNames, ',' ), formula ) );
This evaluates fine for native MATLAB functions. But there's a particular case of a function (named Func1) I made myself that not only needs the list of variables but also an object as argument, like this:
function output = Func1( anObject, varNames )
% do some stuff with the object and the vars
end
For this particular function, I've tried doing this:
Func2 = str2func( sprintf( '#(%s,%s) %s', "objectToPassToFunc1", strjoin( varNames, ',' ), "Func1(objectToPass,""" + strjoin( varNames, '","' ) +""")" ) )
...which doesn't throw an error, but Func1 doesn't receive the objectToPassToFunc1, instead it gets values from one of the variables in varNames. And I don't know why.
So how can I correctly pass the object to Func1????
Matlab doesn't care about the type of arguments you pass to a function. As a matter of fact, the input could be scalar, vector, matrix, and even an object of a class. See the following example.
classdef ClassA
methods
function print(~)
disp('method print() is called.');
end
end
end
This class has only one method. Now, let us define an anonymous function func which accepts one input.
func = #(arg) arg.print;
Notice that we explicitly assume that the input is an object of ClassA. If you pass another type of data to this function, Matlab will throw an error. To test the code,
obj = ClassA;
func = #(arg) arg.print;
func(obj)
To avoid the error, you may need to check the type of the input before using it. For example,
function [] = func(arg)
% check if arg is an object of ClassA
if isa(arg,'ClassA')
arg.print;
end
end
Now you can pass different types for the input without getting an error.
So I have a function like so:
function foo(a, b, c=0, d=10, e=false) {
// ...
}
I would like to call this function with specific inputs, but not necessarily need to list them in order in the input. So like:
foo("bar", "skurr", e=true);
I know in python you can call functions this way, but it seems there is another method I am unaware of for js.
I have tried inputting an object but that did not work since it just uses the object as the first parameter of the function.
foo({a: "bar", b: "skurr", e: true});
How do I call functions in this manner in JavaScript?
One option uses the "object as first argument" as you've described, but the syntax is a bit odd. Consider:
function foo({a, b=0}) { console.log(a,b); }
This defines a function which requires an object as a first argument, and imposes structural constraints on that object. In particular, the following will work:
foo({a:1}); // output: 1 0
foo({a:1, b:2}); // output: 1 2
foo({}); // output: undefined 0
foo({a:1, b:2, c: 3}); // output: 1 2 /* c is ignored */
While the following will throw an error:
foo(); // TypeError: Cannot destructure property `a` of 'undefined' or 'null'
Another option, which is something you see a lot, is an idiom of the form:
function foo(some_object) { let {a,b} = some_object; console.log(a,b); }
Both of these are instances of destructuring. As far as I know it's the closest you'll get to python-like syntax (this answer gives perhaps some more exposition and I give a perhaps too thorough analysis of the formal language which explains the observed effects ES6 destructuring object assignment function parameter default value)
You can specify undefined for the values you want to default. This works because omitted values are also undefined. In your case, this would be:
function foo(a, b, c = 0, d = 10, e = false) {
// ...
}
// call:
foo("bar", "skurr", undefined, undefined, true);
Note that the above example is bad practice. If you have more than a few parameters (arguments), you should consider using objects and destructuring instead:
function foo({a, b, c = 0, d = 10, e = false} = {}) {
// ...
}
// call:
foo({a: "bar", b: "skurr", e: true});
I've been learning lua and can't seem to make a simple implementation of this binary tree work...
function createTree(tree, max)
if max > 0 then
tree = {data = max, left = {}, right = {}}
createTree(tree.left, max - 1)
createTree(tree.right, max - 1)
end
end
function printTree(tree)
if tree then
print(tree.data)
printTree(tree.left)
printTree(tree.right)
end
end
tree = {}
createTree(tree, 3)
printTree(tree)
the program just returns nil after execution. I've searched around the web to understand how argument passing works in lua (if it is by reference or by value) and found out that some types are passed by reference (like tables and functions) while others by value. Still, I made the global variable "tree" a table before passing it to the "createTree" function, and I even initialized "left" and "right" to be empty tables inside of "createTree" for the same purpose. What am I doing wrong?
It is probably necessary to initialize not by a new table, but only to set its values.
function createTree(tree, max)
if max > 0 then
tree.data = max
tree.left = {}
tree.right = {}
createTree(tree.left, max - 1)
createTree(tree.right, max - 1)
end
end
in Lua, arguments are passed by value. Assigning to an argument does not change the original variable.
Try this:
function createTree(max)
if max == 0 then
return nil
else
return {data = max, left = createTree(max-1), right = createTree(max-1)}
end
end
It is safe to think that for the most of the cases lua passes arguments by value. But for any object other than a number (numbers aren't objects actually), the "value" is actually a pointer to the said object.
When you do something like a={1,2,3} or b="asda" the values on the right are allocated somewhere dynamically, and a and b only get addresses of those. Thus, when you pass a to the function fun(a), the pointer is copied to a new variable inside function, but the a itself is unaffected:
function fun(p)
--p stores address of the same object, but `p` is not `a`
p[1]=3--by using the address you can
p[4]=1--alter the contents of the object
p[2]=nil--this will be seen outside
q={}
p={}--here you assign address of another object to the pointer
p=q--(here too)
end
Functions are also represented by pointers to them, you can use debug library to tinker with function object (change upvalues for example), this may affect how function executes, but, once again, you can not change where external references are pointing.
Strings are immutable objects, you can pass them around, there is a library that does stuff to them, but all the functions in that library return new string. So once, again external variable b from b="asda" would not be affected if you tried to do something with "asda" string inside the function.
I've seen conditional statements where the condition is just a variable, which is not a boolean variable. The variable is for an object.
if (myVariable) {
doThis();
}
It seems to be checking if myVariable is null or not. Is that all it is doing? Is this good programming practice? Wouldn't it be better to do this?
if (myVariable != null) {
doThis();
}
It seems much clearer that way.
To properly answer your question:
Using an if statement with an object like that, will check if the object exists.
So if object is null or undefined it will evaluate to the equivalent of false otherwise it will be the equivalent of true.
As far as "good programming practice" goes, that is very opinion based and best left out of StackOverflow.
There is no performance hit and you will find it very common in ECMAScript based languages (like AS3 and JS) - However, many stricter languages (like C# for instance) require an explicit Boolean check so if you program in multiple languages you may find it easier to be consistent.
It's entirely up to you!
Here are some additional examples you may want to consider:
var str:String;
if(str) //will evaluate as false as str is null/undefined
if(str = "myValue") //will evaluate true, as it will use the new assigned value of the var and you're allowed to assign values inside an if condition (though it's ugly and typically uneccessary)
var num:Number;
if(num) //will evaluate as false
num = 1;
if(num) //will evaluate as true
num = 0;
if(num) //will evaluate as false since num is 0
num = -1;
if(num) //will evaluate as true
var obj:Object
if(obj) //will evaluate false
obj = {};
if(obj) //will evaluate true (even though the object is empty, it exists)
var func:Function;
if(func) //false
func = function(){};
if(func) //true - the function exists
function foo():Boolean { return false; }
if(foo) //true - the function exists
if(foo()) //false, the return of the function is false
function foo1():void { return; };
if(foo1()) //false as there is no return type
if (myVariable) // fine but not really explicit.
I usually use:
if (myVariable !== null) // more readable to me
I'm struggling a bit with this: I need a function that takes any function
of type fun(Any*) : Boolean as parameter, evaluates the function and returns true or
false, depending on the success of the function evaluation.
Essentially, what I need is a function type that allows any number and any type of parameter but the function must return Boolean.
Which would allow me to write functions like:
def checkLenght(str : String, length : Int) : Boolean ={
if (str.lenght == length)}
or
def ceckAB(a : Int, b : Int) : Boolean = {
if(a < b && a >= 23 && b < 42) }
so that, for example
eval(checkLenght(abc, 3)) //returns true
eval(ceckAB(4,1)) // returns false
I thought, a function type of:
type CheckFunction = (Any*) => Boolean
may does the trick but I struggle with writing the generic eval function.
Any advise?
Thank you
Solution:
The function requires
1) Another function of return type Boolean: "(func : => Boolean)"
2) Return type Boolean ": Boolean"
3) Returns the value of the passed function-parameter: " = func"
Altogether the function is:
def eval(func : => Boolean) : Boolean = func
It amazes me over again how simple simple things are in Scala.
As pointed out by the comments, this is a rather unusual function with no obvious
sense. Just a word about the underlying reasons.
Motivation:
There were a lot of question about the underlying motivation, so here a short
summary why such a function is needed.
Essentially, there are two reasons.
First one is about moving the failure handling away from the function itself
into a handler function. This preserves the purity of the check function and even allows
re-usage of generic checks.
Second, it's all about "pluggable failure handling". This means, the eval function only
tells if a failure happened (or not). In case of a failure, a handler is called through an interface. The implementation of the handler can be swapped using profiles as required.
Why?
Swapping profiles means, I code my checks and functions as usual but by switching the
profile, I switch the handler which means I can chose between full-stop, console print out, email alert, SNMP notification, push message... you name it. To do so, I need to decouple the check function from its evaluation and from its handling. That's the motivation for such a rather strange looking eval function.
And for the sake of completeness, I've already implemented all that stuff but was I facing the limitation of only handling trivial checks i.e. check(Boolean*) which is neat but often I would prefer to write a function to do more sophisticated checks.
Solved
The function is defined by returning the value of the passed function:
def eval(func : => Boolean) : Boolean = {func}
I can't say that I really understand your motivations for wanting to do what you want to do, but I guess that's beside the point. Maybe the eval function will check something before invoking the supplied function and not invoke that other function (like a fast fail) given some certain condition. Maybe you do some post checking after invoking the function and change the result based on something else. Either way, I suppose you could accomplish something similar to what you want with code looking like this:
def main(args: Array[String]) {
val str = "hello world"
println(eval(checkLength(str, 3)))
println(eval(intsEqual(1,1)))
}
def eval(func: => Boolean):Boolean = {
//Do whetever you want before invoking func, maybe
//not even invoke it if some other condition is present
val fres = func
//Maybe change something here before returning based on post conditions
fres
}
def checkLength(s:String, len:Int) = s.length() == len
def intsEqual(a:Int, b:Int) = a == b
If you really want the eval function to be able to support any function that takes any types of args and returns a Boolean, then using a by-name function like this, and then leveraging closure inside the by-name function to pass any params along to whatever actual function you want to invoke. A better way to demonstrate this is as follows:
def checkMyString(str:String, len:Int) = {
eval(str.length == len)
}
It's probably hard to see that the check str.length == len is not invoked unless eval decides to invoke it until you expand it to it's true form:
def checkMyString(str:String, len:Int) = {
def check = {
str.length == len
}
eval(check)
}
Here, the nested function check has access to str and len due to closure, and this will allow you to get around the requirement that eval must be able to invoke a function with any params that returns a Boolean.
This is just one way to solve your problem, and it might not even be suitable given your needs, but I just wanted to throw it out there.
If your input functions only have 2 arguments, like your two examples, you can write a semi generic function take takes all functions with two arguments of any type:
def eval[A,B](func: (A,B) => Boolean, arg1: A, arg2: B) = {
func(arg1, arg2)
}
def checkLength(str: String, length: Int) : Boolean = {
str.length == length
}
eval(checkLength, "ham", 4)
res0: Boolean = false
But if you want to support functions with more arguments, you would have to write one eval function for three arguments, four arguments, etc
Maybe there is a better way that can handle all cases?