var a=[1,2,3]
var b=[1,2,3]
var c=[1,2,4]
System.print(a==b)
System.print(a==c)
How do I check if two lists are equal? I tried the equality operator == but this doesn't work; it prints false and false
There is no built-in operator or algorithm for list equality in wren - you must check the elements individually.
An example algorithm is available here: https://github.com/minirop/wren-helpers/blob/master/algorithms/algorithm.wren#L6-L17
static equal(list1, list2) {
if (list1.count != list2.count) {
return false
}
for (i in 0...list1.count) {
if (list1[i] != list2[i]) {
return false
}
}
return true
}
There is an open discussion on whether to add support for an equality list function: here https://github.com/wren-lang/wren/issues/606
Related
I'm trying to find a value in a list of objects in kotlin, using for it "filter", but I need to return true or false if the value is found, but filter returns me a list of object in the case of match.
t.filter { it.retailerId == value }
¿How I can return a boolean when I find this value in the list of objects?
If you need that the element is exactly one:
t.filter { it.retailerId == value }.size == 1
if not:
t.any { it.retailerId == value }
With foldRight and a break when you found it:
t.foldRight(false) {val, res ->
if(it.retailerId == value) {
return#foldRight true
} else {
res
}
}
In alternative to firstOrNull you can also use any with the same predicate:
val found = t.any { it.retailerId == value }
You can use firstOrNull() with the specific predicate:
val found = t.firstOrNull { it.retailerId == value } != null
If firstOrNull() does not return null this means that the value is found.
For single element
list.first { it.type == 2 (eg: conditions) }
or
list.firstOrNull { it.type == 2 (eg: conditions) }
For list of elements
list.filter { it.type == 2 (eg: conditions) }
Kotlin has this nice extension function which u can use
if (none { it.isSelected == true }) {
first().isSelected = true
}
I have a vector of pointers to class instances I created with multiple values in it called Record
it has a value called, when I access them I
bool recordDeleted;
bool recordOwnership;
vector<Record*> RecordsVec
I want to create a function that would do something like,
bool func()
{
for (auto it = RecordsVec.begin(); it < RecordsVec.end(); it++)
{
// check whether recordDeleted is true // or recordOwnership == true)
}
// if all are true
// return true
// else
// return false
}
what is the most efficient way to do this ?
Pretty simple:
bool allDeleted() {
return std::all_of(begin(RecordsVec), end(RecordsVec), [](Record *r) {
return r->recordDeleted;
});
}
And the same for your ownership flag, of course.
The following filter method will return true if the elements in the array of Bool is all true.
print([false, true].filter({!$0}).isEmpty) // yields false
print([true, true].filter({!$0}).isEmpty) // yields true
How do I create an extension method on the Array in Swift 3 that will allow me to represent it like this:
[false, true].allElementsTrue()
This should answer your question:
extension Collection where Iterator.Element == Bool {
var allElementsTrue: Bool {
return self.filter({!$0}).isEmpty
}
}
or
extension Collection where Iterator.Element == Bool {
func allElementsTrue() -> Bool {
return self.filter({!$0}).isEmpty
}
}
But I prefer using computed properties when there's no parameter to give.
Note: as an alternative you could also return !self.contains(false) to get the same result more efficiently (short-circuiting).
I'm sure you've been there. You want to say "if flib do this, if flob do that, if flab do diet, etc" where any number of them can be true, then at the end you want an "if you didn't do ANY of them".
For example (the examples below are in Swift, as I've been playing with it, but I think the situation is the same in most languages):
let thing = 101
var isInteresting = false
if (thing % 3 == 0) {
println("\"\(thing)\" is a multiple of three.")
isInteresting = true
}
if (thing > 100) {
println("\"\(thing)\" is greater than one hundred.")
isInteresting = true
}
if (thing > 1000) {
println("\"\(thing)\" is greater than one thousand.")
isInteresting = true
}
if !isInteresting {
println("\"\(thing)\" is boring.")
}
I find keeping track of a boolean to tell me whether I did anything or not kinda ungainly.
The only other way I came up with was this:
let thing = 101
let isAMultipleOfThree = (thing % 3 == 0)
let isGreaterThan100 = (thing > 100)
let isGreaterThan1000 = (thing > 1000)
if isAMultipleOfThree {
println("\"\(thing)\" is a multiple of three.")
}
if isGreaterThan100 {
println("\"\(thing)\" is greater than one hundred.")
}
if isGreaterThan1000 {
println("\"\(thing)\" is greater than one thousand.")
}
if !(isAMultipleOfThree || isGreaterThan100 || isGreaterThan1000 ) {
println("\"\(thing)\" is boring.")
}
but if anything that's worse (if you add a new clause you need to remember to add it in three places.
So my question is, is there a neat, succinct way of doing this?
I'm dreaming of an imaginary switch-like statement:
switchif { //Would have fallthrough where every case condition is checked
case thing % 3 == 0:
println("\"\(thing)\" is a multiple of three.")
case thing >100 :
println("\"\(thing)\" is greater than one hundred.")
case thing > 1000:
println("\"\(thing)\" is greater than one thousand.")
none: //Unlike 'default' this would only occur if none of the above did
println("\"\(thing)\" is boring.")
}
It's a good question that does not have a perfect answer. However, here's one other idea in addition to those you suggest: Encapsulate the testing machinery in a procedure to allow the calling code at least to be a bit more streamlined.
Specifically, for your example, the calling code can be this:
if (! doInterestingStuff(101)) {
println("\"\(thing)\" is boring.");
}
If testing is encapsulated into a procedure:
public boolean doInterestingStuff(int thing) {
var isInteresting = false
if (thing % 3 == 0) {
println("\"\(thing)\" is a multiple of three.")
isInteresting = true
}
if (thing > 100) {
println("\"\(thing)\" is greater than one hundred.")
isInteresting = true
}
if (thing > 1000) {
println("\"\(thing)\" is greater than one thousand.")
isInteresting = true
}
return isInteresting
}
I'm not sure how you'd do this in Swift, but since you didn't give a language tag I'll answer in C++.
The key to this is that && is short circuiting, and the second part won't be evaluated when the first part is false. It's the same idea as your boolean flag, but it's a little more automated.
struct Tracker
{
Tracker() : any(false) { }
bool operator()() { any = true; return true; }
bool any;
};
int thing = 101;
Tracker tracker;
if (thing % 3 == 0 && tracker()) {
printf("\"%d\" is a multiple of three.\n", thing);
}
if (thing > 100 && tracker()) {
printf("\"%d\" is greater than one hundred.\n", thing);
}
if (thing > 1000 && tracker()) {
printf("\"%d\" is greater than one thousand.\n", thing);
}
if (!tracker.any) {
printf("\"%d\" is boring.\n", thing);
}
See it in action: http://ideone.com/6MQYY2
kjhughes' answer inspired me a little:
Perhaps one could write a global function that accepts an indeterminate number of key-value pairs (or even just two element arrays), where the key is a comparison and the value is the statement to run if it's true. Then return false if none of them were run, otherwise true.
Update:
Tried it, it's horrible!
//Function:
func ifNone(ifNoneFunc:()->Void, tests: Bool...)
{
var oneTestPassed = false
for test in tests
{
oneTestPassed |= test
}
if(!oneTestPassed)
{
ifNoneFunc()
}
}
//Example:
let thisThing = 7
ifNone(
{
println("\(thisThing) is boring")
},
{
if(thisThing % 10 == 0)
{
println("\"\(thisThing)\" is a multiple of 10")
return true
}
else
{
return false
}
}(),
{
if(thisThing % 3 == 0)
{
println("\"\(thisThing)\" is a multiple of 3")
return true
}
else
{
return false
}
}(),
{
if(thisThing > 1_000_000)
{
println("\"\(thisThing)\" is over a million!!")
return true
}
else
{
return false
}
}()
)
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
Sorry if this question is not suited for SO.
I have a C++ function that approximately looks like MyFun() given below.
From this function I am calling some(say around 30) other functions that returns a boolean variable (true means success and false means failure). If any of these functions returns false, I have to return false from MyFun() too. Also, I am not supposed to exit immediately (without calling the remaining functions) if an intermediate function call fails.
Currently I am doing this as given below, but feel like there could be a more neat/concise way to handle this. Any suggestion is appreciated.
Many Thanks.
bool MyFun() // fn that returns false on failure
{
bool Result = true;
if (false == AnotherFn1()) // Another fn that returns false on failure
{
Result = false;
}
if (false == AnotherFn2()) // Another fn that returns false on failure
{
Result = false;
}
// Repeat this a number of times.
.
.
.
if (false == Result)
{
cout << "Some function call failed";
}
return Result;
}
I would replace each if statement with a more coincise bitwise AND assignment:
bool MyFun() // fn that returns false on failure
{
bool Result = true;
Result &= AnotherFn1(); // Another fn that returns false on failure
Result &= AnotherFn2(); // Another fn that returns false on failure
// Repeat this a number of times.
.
.
.
if (false == Result)
{
cout << "Some function call failed";
}
return Result;
}
Use something like a std::vector of std::function. It is a lot more maintenable.
Example: http://ideone.com/0voxRl
// List all the function you want to evaluate
std::vector<std::function<bool()>> functions = {
my_func1,
my_func2,
my_func3,
my_func4
};
// Evaluate all the function returning the number of function that did fail.
unsigned long failure =
std::count_if(functions.begin(), functions.end(),
[](const std::function<bool()>& function) { return !function(); });
If you want to stop when a function fail, you just have to use std::all_of instead of std::count_if. You dissociate the control flow from the function list and that is, in my opinion, a good thing.
You can improve this by using a map of function with name as key that will allows you to output which function failed:
std::map<std::string, std::function<bool()>> function_map;
bool MyFun() // fn that returns false on failure
{
bool Result = true;
// if need to call every function, despite of the Result of the previous
Result = AnotherFn1() && Result;
Result = AnotherFn2() && Result;
// if need to avoid calling any other function after some failure
Result = Result && AnotherFn1();
Result = Result && AnotherFn2();
return Result;
}
Instead of
if (false == AnotherFn1()) // Another fn that returns false on failure
{
Result = false;
}
if (false == AnotherFn2()) // Another fn that returns false on failure
{
Result = false;
}
if (false == AnotherFn3()) // Another fn that returns false on failure
{
Result = false;
}
begin to use booleans as what they are, truth values:
if (!AnotherFn1()) // Another fn that returns false on failure
{
Result = false;
}
if (!AnotherFn2()) // Another fn that returns false on failure
{
Result = false;
}
if (!AnotherFn3()) // Another fn that returns false on failure
{
Result = false;
}
Then, all those conditions have the same code; they are basically part of one big condition:
if ( !AnotherFn1()
| !AnotherFn2()
| !AnotherFn3())
{
Result = false;
}
For your specific problem, where you want all functions be called, even if you know early you'll return false, it is important to not use the short circuiting operators && and ||. Using the eager bitwise operators | and & is really a hack, because they are bitwise and not boolean (and thus hide intent), but work in your situation iff AnotherFn? return strict bools.
You can negate what you do inside; less negations yield better code:
Result = false;
if ( AnotherFn1()
& AnotherFn2()
& AnotherFn3())
{
Result = true;
}
and then you can rid these assignments and instead return straightly:
if ( AnotherFn1()
& AnotherFn2()
& AnotherFn3())
{
return true;
}
cout << "something bad happened";
return false;
Summary
Old:
bool MyFun() // fn that returns false on failure
{
bool Result = true;
if (false == AnotherFn1()) // Another fn that returns false on failure
{
Result = false;
}
if (false == AnotherFn2()) // Another fn that returns false on failure
{
Result = false;
}
// Repeat this a number of times.
.
.
.
if (false == Result)
{
cout << "Some function call failed";
}
return Result;
}
New:
bool MyFun() // fn that returns false on failure
{
if (AnotherFn1() &
AnotherFn2() &
AnotherFn3())
{
return true;
}
cout << "Some function call failed";
return false;
}
There are more possible improvements, e.g. using exceptions instead of error codes, but don't be tempted to handle "expections" instead.
! can be used as a cleaner alternative to false
Like this:
bool MyFun() // fn that returns false on failure
{
bool Result = true;
if (!AnotherFn1()) // Another fn that returns false on failure
{
Result = false;
}
if (!AnotherFn2()) // Another fn that returns false on failure
{
Result = false;
}
// Repeat this a number of times.
.
.
.
if (!Result)
{
cout << "Some function call failed";
}
return Result;
}
how about using exceptions to handle failure:a neat exemple
the main question is, are the function call interdependant or not? can some be skipped if a previous one failed? ...