return type of bool function - boolean

what is the return type of this sort of bool function...... i know the return type is either true of false but this seems complicated when you have got like this..
bool mypredicate (int i, int j) {
return (i==j);
}
this bool function are used in a library function called equal...... another example is....
bool compare(int a, int b){
return a<b;
}
so what are the perspective here to return type of these bool function.when is goes true & false....

Your functions mypredicate and compare are merely thin wrappers over the binary operators == and <. Operators are like functions: they take a number of arguments of a given type, and return a result of a given type.
For example, imagine a function bool operator==(int a, int b) with the following specification:
if a equals b then return true
otherwise return false
And a function bool operator<(int a, int b) with the following specification:
if a is strictly lesser than b then return true
otherwise return false.
Then you could write:
bool mypredicate (int i, int j) {
return operator==(i, j);
}
bool compare(int a, int b){
return operator<(a, b);
}
For convenience, most programming languages allow you to use a shorter, functionnaly equivalent syntax: i == j and a < b.

Related

Avoid duplication of null type checking in Dart

My current goal is to remove this code duplication:
final int? myNullableInt = 10;
/// Everywhere I need to do this null verification:
if (myNullableInt == null) return null;
return someOtherMethodThatReceivesANonNullableInt(myNullableInt);
I want to convert to something like we have in Kotlin:
final int? myNullableInt = 10;
return myNullableInt?.apply((myInt) => someOtherMethodThatReceivesANonNullableInt(myInt));
I did it:
extension ApplyIfNotNull on Object? {
T? apply<T extends Object?>(Object? obj, T? Function(Object) fn) {
if (obj == null) return null;
return fn(obj);
}
}
But this gives me a static error:
The argument type 'Object' can't be assigned to the parameter type 'int'.
Note: this should work with all types, e.g ints, Strings, double and MyOwnClassTypes.
Is there something I can do? or am I missing something?
extension ApplyIfNotNull on Object? {
T? apply<T extends Object?>(Object? obj, T? Function(Object) fn) {
if (obj == null) return null;
return fn(obj);
}
}
That doesn't work because it declares that the callback be capable of accepting any Object argument, but you're presumably trying to use it with a function that accepts only an int argument. It's also unclear why you've made an extension method since it doesn't involve the receiver (this) at all.
You need to make your function generic on the callback's argument type as well:
R? applyIfNotNull<R, T>(T? obj, R Function(T) f) =>
(obj == null) ? null : f(obj);
(That's the same as what I suggested in https://github.com/dart-lang/language/issues/360#issuecomment-502423488 but with the arguments reversed.)
Or, as an extension method, so that it can work on this instead of having the extra obj argument:
extension ApplyIfNotNull<T> on T? {
R? apply<R>(R Function(T) f) {
// Local variable to allow automatic type promotion. Also see:
// <https://github.com/dart-lang/language/issues/1397>
var self = this;
return (self == null) ? null : f(self);
}
}
Also see https://github.com/dart-lang/language/issues/360 for the existing language feature request and for some other suggested workarounds in the meantime.

How to check if FileSystemEntity is a Directory [duplicate]

Let's say I have:
class Test<T> {
void method() {
if (T is int) {
// T is int
}
if (T == int) {
// T is int
}
}
}
I know I can override == operator but what's the main difference between == and is in Dart if I don't override any operator.
Edit:
Say I have
extension MyIterable<T extends num> on Iterable<T> {
T sum() {
T total = T is int ? 0 : 0.0; // setting `T == int` works
for (T item in this) {
total += item;
}
return total;
}
}
And when I use my extension method with something like:
var addition = MyIterable([1, 2, 3]).sum();
I get this error:
type 'double' is not a subtype of type 'int'
identical(x, y) checks if x is the same object as y.
x == y checks whether x should be considered equal to y. The default implementation for operator == is the same as identical(), but operator == can be overridden to do deep equality checks (or in theory could be pathological and be implemented to do anything).
x is T checks whether x has type T. x is an object instance.
class MyClass {
MyClass(this.x);
int x;
#override
bool operator==(dynamic other) {
return runtimeType == other.runtimeType && x == other.x;
}
#override
int get hashCode => x.hashCode;
}
void main() {
var c1 = MyClass(42);
var c2 = MyClass(42);
var sameC = c1;
print(identical(c1, c2)); // Prints: false
print(identical(c1, sameC)); // Prints: true
print(c1 == c2); // Prints: true
print(c1 == sameC); // Prints: true
print(c1 is MyClass); // Prints: true
print(c1 is c1); // Illegal. The right-hand-side must be a type.
print(MyClass is MyClass); // Prints: false
}
Note the last case: MyClass is MyClass is false because the left-hand-side is a type, not an instance of MyClass. (MyClass is Type would be true, however.)
In your code, T is int is incorrect because both sides are types. You do want T == int in that case. Note that T == int would check for an exact type and would not be true if one is a derived type of the other (e.g. int == num would be false).
Basically, == is equality operator and "is" is the instanceof operator of Dart (If you come from Java background, if not, it basically tells you if something is of type something).
Use == for equality, when you want to check if two objects are equal. You can implement the == operator (method) in your class to define on what basis do you want to judge if two objects are equal.
Take this example:
class Car {
String model;
String brand;
Car(this.model, this.brand);
bool operator == (otherObj) {
return (otherObj is Car && other.brand == brand); //or however you want to check
//On the above line, we use "is" to check if otherObj is of type Car
}
}
Now you can check if two cars are "equal" based on the condition that you have defined.
void main() {
final Car micra = Car("Micra", "Nissan");
print(micra == Car("Micra", "Nissan")); // true
print(micra is Car("Micra", "Nissan")); // true
}
Hence, == is something you use to decide if two objects are equal, you can override and set it as per your expectations on how two objects should be considered equal.
On the other hand, "is" basically tells you if an instance is of type object (micra is of type Car here).

How do I check if a value is a number (even or odd) with type double in Dart?

How do I check if a value is a number (even or odd) with type double in Dart?
double value = 2.5;
print(value.floor().isEven ? "It's even" : "It's odd");
You can go traditional with String evenOrOdd = number %2 == 0?'even':'odd'
There are native methods for int to achieve that purposes. You can convert the number to an int and call number.isOdd, number.isEven...
Documentation:
abstract class int extends num {
/// Returns true if and only if this integer is odd.
bool get isOdd;
// Returns true if and only if this integer is even.
bool get isEven;
}
Here is the code to detect from String.
bool isDouble(String? s) {
if (s == null) {
return false;
}
if(int.tryParse(s)!=null){
return false;
}
return double.tryParse(s)!= null;
}

How to assign a function inline to a value in Dart?

I like to assign the return value of a function to a variable, but inline. The following is how you would do it not inline.
bool isValid() {
if(a == b) return true;
if(a == c) return true;
return false;
}
bool result = isValid();
What I want is something like
bool result = () {
if(a == b) return true;
if(a == c) return true;
return false;
}
However it displays the error
The argument type 'Null Function()' can't be assigned to the parameter type 'bool'
How do I achieve this?
You are defining a lambda expression. This works the same way as in Javascript, Typescript or many other languages.
bool result = () {
if(a == b) return true;
if(a == c) return true;
return false;
}
This code defines an anonymous function of type () -> bool (accepts no parameters and returns bool). And the actual type of the result variable is bool so the compilation is broken (() -> bool and bool are non-matching types).
To make it correct just call the function to get the result.
bool result = () {
if(a == b) return true;
if(a == c) return true;
return false;
}();
Now you define an anonymous function (lambda) and then call it so the result is bool. Types are matching and there's no error.
This is rather an uncommon behaviour to define the function and immediately call it. It's used in Javascript to create a separate scope for variables using closures (some kind of private variables). I would recommend you to move the code to some kind of class or pass a, b, c parameters directly to the function:
bool isValid(a, b, c) {
/* Your code */
}
It's more generic that way and could be reused. Immediately called lambda is often a sign of bad design.

Passing the correct type to addch() [ncurses, Linux]

In following a tutorial on how to use ncurses with swift I have been facing the error:
main.swift:31:15: error: cannot convert value of type 'UInt?' to expected argument type 'chtype' (aka 'UInt32')
addch(UInt("*"))
^~~~~~~~~
It complains about the type, but when I change it to UInt32 the error changes to error: ambiguous use of 'init' addch(UInt32("*"))
Question
How to pass the correct value type to addch?
The entire code for reference:
import Foundation
import CNCURSES
import Glibc
enum Signal:Int32 {
case INT = 2
case WINCH = 28
}
typealias SignalHandler = __sighandler_t
func trap(signum:Signal, action:#escaping SignalHandler) {
signal(signum.rawValue, action)
}
func getmaxyx(window:UnsafeMutablePointer<WINDOW>, y:inout Int32, x:inout Int32) {
x = getmaxx(window)
y = getmaxy(window)
}
func getcuryx(window:UnsafeMutablePointer<WINDOW>, y:inout Int32, x:inout Int32) {
x = getcurx(window)
y = getcury(window)
}
func drawbox(numlines:Int32, numcols:Int32) {
for y in 0...numlines-1 {
for x in 0...numcols {
move(y, x)
if y == 0 || y == numlines-1 {
addch(UInt("*"))
} else {
if x == 0 || x == numcols {
addch(UInt("*"))
}
}
}
}
refresh()
}
[...]
initscr()
noecho()
curs_set(0)
getmaxyx(window:stdscr, y:&maxy, x:&maxx)
drawbox(numlines:maxy, numcols:maxx)
center(text:"Hello world!", numlines:maxy, numcols:maxx)
while true {
select(0, nil, nil, nil, nil)
}
Seeing the error message, you need to pass a UInt32 value to addch(_:).
The return type of UInt("*") is UInt?, and its actual value is always nil. (Simple String to UInt conversion tries to interpret the String as decimal integer.)
When you want a character code as UInt32, you may need to write something like this:
addch(("*" as UnicodeScalar).value)
If your code would have many more addch(_:) calls, you can define a simple wrapper for it.
For example:
func addCh(_ us: UnicodeScalar) {
addch(us.value)
}
addCh("*")
With explicitly annotating as UnicodeScalar, String Literals are interpreted as UnicodeScalar and its value property is of type UInt32.
The correct (and documented type) is chtype:
int addch(const chtype ch);
int waddch(WINDOW *win, const chtype ch);
int mvaddch(int y, int x, const chtype ch);
int mvwaddch(WINDOW *win, int y, int x, const chtype ch);
int echochar(const chtype ch);
int wechochar(WINDOW *win, const chtype ch);
The number of bits in chtype depends upon the system. In ncurses' header files, it is by default declared as unsigned, but that can be overridden when configuring/building ncurses.
X/Open (see addch and <curses.h>) says nothing more explicit than that.
Of course, whatever it happens to be in swift is an implementation detail of the binding, and unless documented, is subject to change.