Dart - Functional Difference Between Conditional Operator vs. If Statement - dart

Why does this work:
var myAnimal = (1 == 1)? 'Cat' : 'Dog'; //OK
myList.forEach((element) => (1 == element)? print('1') : print('Not 1')); //OK
But this doesn't?
var myAnimal = if(1 == 1) 'Cat'; else 'Dog';
//Expected an identifier, but got 'if'
myList.forEach((element) => if(1 == element) print('1'); else print('Not 1'));
//Expected an identifier, but got 'if'
I've been treating it like a given but I don't actually know why.

Because one is a statement (if) and other is an expression (ternary).
A statement "does" something, while an expression evaluates to a value.
The => in your function acts similarly to a return keyword.
While you can do something like: return print('statement'); . You can't return two of those statements: return: print('statement'); print('statement');

Related

Can dafny assert cope with "! false"

The final commented out assert will not validate but when run the if statement above will prints.
OUTPUT
ohb= true
ohx= false
palin(xe) == false
ohx ==false
function method palin(a:seq<int>) :bool {
forall i:int :: (0<=i && i<(|a|/2)) ==> a[i]==a[|a|-i -1]
}
method Main() {
var xe:seq<int> := [0,1,2,3,0];
var se:seq<int> := [0,1,2,1,0];
var ohb := palin(se);
var ohx :bool := palin(xe);
print "ohb= ",ohb,"\n";
print "ohx= ",ohx,"\n";
assert palin(se);
if (palin(xe) == false) {print "palin(xe) == false\n";}
if (!ohx) {print "ohx ==false\n";}
//assert !ohx;
}
A failing assert means the verifier cannot automatically find a proof. If you think the property holds, you need to write the proof (or part of the proof).
For your program, proving that something is not a palindrome comes down to showing a position that violates the palindrome property. In terms of logic, you're trying to prove the negation of a forall, which is an exists, and to prove an exists you'll need to supply the witness for the bound variable i.
In your example, the following suffices:
predicate method palin(a: seq<int>) {
forall i :: 0 <= i < |a| / 2 ==> a[i] == a[|a| - i - 1]
}
method Main() {
var xe := [0,1,2,3,0];
var se := [0,1,2,1,0];
var ohb := palin(se);
var ohx := palin(xe);
print "ohb= ", ohb, "\n";
print "ohx= ", ohx, "\n";
assert palin(se);
if palin(xe) == false { print "palin(xe) == false\n"; }
if !ohx { print "ohx == false\n"; }
assert !ohx by {
assert xe[1] != xe[3];
}
}

How to create inline if without else case

Does Dart support a syntax to have an inline if without an else case? I sometimes find myself in a situation to create a flutter layout where this might be really helpful
new Row(children: <Widget>[
new Text(item.name),
item.name2 != null ? new Text(item.name2) : new Container(),
]
In this example the empty container is unnecessary so I was hoping for something like this:
new Row(children: <Widget>[
new Text(item.name),
item.name2 != null ? new Text(item.name2),
]
there is no inline if without else
but in your case you're using if only to check only if it's null or not
dart have :
x = someVar ?? 0
here dart checks if someVar == null ? if true sets x value to 0, if false sets it to someVar value
but flutter will never let you add null to it's widget tree, so your can't use it in row/col
You can do this:
myVar == null ? 0 : myVar
If myVar is null then is 0, else then myVar
If you need to call a function you can use like this:
String s; //null
s == null ? print("if shorthand working") : {};
For variable assignment:
String c = "not null value";
String b; //null
var a = b ?? c;
Now a = c.
Visual Studio Code tip: add this to ignore linting for a line
// ignore: unnecessary_statements
In general, the "inline if" can be written in darts as follows:
<condition> ? <expression 1> : <expression 2>
So that if <condition> evaluates to True, then <expression 1> is returned and otherwise <expression 2>.
For example:
result = myVar == null ? 0 : myVar ;
// if myVar is null -> result = 0
// if myVar is not null -> result = myVar
There is actually plans to include a similar feature into the Dart language itself.
For a preview of how it would look like, take a look at this article by Remi
https://medium.com/flutter-community/quick-tip-sync-a-taste-of-the-future-9be4cd6993f4
And some accompanying Github issues
https://github.com/flutter/flutter/issues/17862
https://github.com/dart-lang/language/issues/47
https://github.com/dart-lang/language/issues/78

What is the default return value of a Dart function?

The function below works even though I intentionally deleted 'return' command:
main() {
add(i) => i + 2; //I intentionally deleted 'return'
print(add(3)); //5
}
But, the function below doesn't work after I intentionally deleted the 'return' command.
main() {
makeAdder(num addBy) {
return (num i) {
addBy + i; //I intentionally deleted 'return'
};
}
var add2 = makeAdder(2);
print(add2(3) ); //expected 5, but null.
}
Edited to clarify my question.
The last sentence in the latter function above, add2(3) doesn't return a value(I expect 5) but just null returns.
My question is why 'addBy + i' of the latter function doesn't return contrary to the fact that 'add(i) => i + 2' of the first function returns 'i + 2'.
Edited again.
The answer is in the fact of '=>' being {return }, not just {}.
main() {
makeAdder(num addBy) => (num i) { return addBy + i; };
var add2 = makeAdder(2);
print(add2(3) ); // 5
}
Even the code below works as '=>' has 'return' command in it.
main() {
makeAdder(num addBy) => (num i) => addBy + i; ;
var add2 = makeAdder(2);
print(add2(3) ); //5
}
In Dart each function without an explicit return someValue; returns null;
The null object does not have a method 'call'.
makeAdder (add2) without return returns null and null(3) leads to the exception.
I would like to quote two important note here. It might help others:
Though Dart is Optionally typed ( meaning, specifying the return type of a function such as int or void is optional ), it always recommended to specify type wherever possible. In your code, as a sign of good programming practice, do mention the return type.
If your function does not return a value then specify void. If you omit the return type then it will by default return null.
All functions return a value. If no return value is specified, the statement return null; is implicitly appended to the function body.

if(function(s)) { statement } (Language C) (Standard return) (+newbie) (+abreviated expressions)

how are you?
int stack_empty(stack *s){
return (s == NULL); /* I dont get this part, it returns what if its null? */
}
int main(){
stack *s;
if(stack_empty(s)){ /* what it means? like... whats the standard return of a function? */
printf("its empty");
}
return 0;
}
My questions are in the comments of the code. Briefly they are:
-> Whats the standard return of a function?
-> What does return something == NULL means?
*I know what NULL, s or == means... my questions lies on those abreviated expressions.
== is a test for equality.
If s is null then s == null is true the expression has a non zero value, so stack_empty will return non zero (probably 1). If s is not null, then s == null is false so the method will return 0.
The if statement is effectively saying if expression is not 0.

Why would you add "or false" to the end of your boolean expression?

I have seen code in lua like this
if (a==b or false) then
what is the purpose of the "or false"?
This is the original code:
Function = function(self, aura, auraID)
-- Store the version.
-- aura.Version = 50000;
-- Fix texmode/glow.
aura.texmode = (aura.texmode == 1 or aura.texmode == true or false);
-- Texture source.
if(aura.owntex or aura.SourceType == PowaAuras.SourceTypes.Icon) then
aura.SourceType = PowaAuras.SourceTypes.Icon;
elseif(aura.wowtex or aura.SourceType == PowaAuras.SourceTypes.WoW) then
aura.SourceType = PowaAuras.SourceTypes.WoW;
elseif(aura.customtex or aura.SourceType == PowaAuras.SourceTypes.Custom) then
aura.SourceType = PowaAuras.SourceTypes.Custom;
elseif(aura.textaura or aura.SourceType == PowaAuras.SourceTypes.Text) then
aura.SourceType = PowaAuras.SourceTypes.Text;
else
aura.SourceType = PowaAuras.SourceTypes.Default;
end
end
And here is another example
-- Iterate over element children.
visible, hidden = self:UpdateScrollList(key, level+1, visible, hidden,
(parentShowing == true and item:GetExpanded() or false));
This looks like a behavior that comes from the syntax:
a=b or false
to initialize a to the value of b or false if b isn't defined.
Within the if statement as you wrote it, I don't see any purpose since the == is evaluated before the or. If they used parenthesis to change the order of operations, then it could be used to validate that b has been defined, e.g.:
> a=nil
> b=nil
> if (a == (b or false)) then print("yikes") else print("aok") end
aok
> if (a == b or false) then print("yikes") else print("aok") end
yikes
It is used to temporarily disable a block of Code.
It's semantics are technically the same as:
#if 0
dead code goes here ...
#endif
It's to explicitly state the value assigned to the expression when none of its prior conditions are true.
In Lua, the and and or expressions return the values that determine their truth values, rather than the flat truth value itself, like this:
function And(A,B)
if A then return B --if A is true, then the agreement of both depends on B
else return A end --otherwise, they're not, because A wasn't
end
function Or(a,b)
if A then return A --if A is true, then it doesn't matter if B was true
else return B end --otherwise, the truth hinges on B's value
end
In Lua, all values other than false and nil evaluate to true in conditional constructions, so this behavior is commonly used as an idiom to describe default values:
local color = color or 'blue' -- if `color` is defined to any value other than
-- `false` (such as any string), it will evaluate
-- as true, and the value will be returned from
-- the `or` statement (so `color` will be assigned
-- its own value and no change will result) -
-- if `color` is not defined, the `or` statement
-- will evaluate its `nil` value as false and
-- return the second value, 'blue'
This idiom can be combined and extended in various ways:
local color = color or self.color
or (favorites and favorites.color)
or (type(favourites)=='table' and favourites.colour)
or get_defaults('color')
or {'red','blue','green','yellow'}[math.random(1,4)]
Traditionally, though, they stay fairly simple, with maybe a few chained or cases before the default value.
That's what we're seeing here: the cases where or false is being used are for the last-case value for the expression.
So, while this:
aura.texmode = (aura.texmode == 1 or aura.texmode == true or false);
could have been written as this with exactly the same effect (since the == comparisons will return either true or false):
aura.texmode = (aura.texmode == 1 or aura.texmode == true);
adding the final or false makes it more obvious when looking at that line that the value can be false.
The same goes for the second example, in which the value is being assigned to an argument.
There is no use, because if a~=b then it will try false, which is ... false and return false anyway ...

Resources