This language bar is your friend. Select your favorite languages!
Select your favorite languages :
- Or search :
Idiom #223 for else loop
Loop through list items checking a condition. Do something else if no matches are found.
A typical use case is looping through a series of containers looking for one that matches a condition. If found, an item is inserted; otherwise, a new container is created.
These are mostly used as an inner nested loop, and in a location where refactoring inner logic into a separate function reduces clarity.
- Clojure
- C++
- C++
- C#
- Dart
- Fortran
- Go
- Groovy
- JS
- Java
- Java
- Java
- Kotlin
- Kotlin
- Lisp
- Lua
- PHP
- Pascal
- Perl
- Python
- Ruby
- Rust
- Rust
- Rust
- Rust
- Rust
(if (seq (filter odd? my-col))
"contains odds"
"no odds found")
(seq (filter pred-fn col)) returns nil when there are no matches, and nil is falsy.
if (std::any_of(items.begin(), items.end(), condition))
baz();
else
DoSomethingElse();
Calls condition(x) on each element in items until one returns true
for _, item := range items {
if item == "baz" {
fmt.Println("found it")
goto exit
}
}
{
fmt.Println("not found")
}
exit:
Go does not have a for...else construct, but a structured goto label works well.
function search(array $haystack, string $needle, callable $doSuccess, callable $doFail)
{
foreach ($haystack as $item) {
if ($item === $needle) {
$doSuccess();
return;
}
}
$doFail();
}
$items = ["foo", "bar", "baz", "qux"];
search(
$items,
"baz",
static function () {
echo "found it";
},
static function () {
echo "not found";
}
);
my $found_match = 0;
foreach my $item (@items) {
if ($item eq 4) {
print "Found $item\n";
$found_match = 1;
last;
}
}
if (!$found_match) {
print "Didn't find what I was looking for\n";
}
if 'search: loop {
for i in items {
if i == &"qux" {
println!("found it");
break 'search false;
}
}
break 'search true
} {
println!("not found!");
}
for within a loop, which is only executed once
'label: {
for &item in items {
if item == "baz" {
println!("found");
break 'label;
}
}
println!("not found");
}
Rust allows you to label scopes, which can then be used together with "break 'label". We can (ab)use this to emulate "for else" loops.
let mut found = false;
for item in items {
if item == &"baz" {
println!("found it");
found = true;
break;
}
}
if !found {
println!("never found it");
}
Rust does not have a for...else construct, so we use a found variable.
items
.iter()
.find(|&&item| item == "rockstar programmer")
.or_else(|| {
println!("NotFound");
Some(&"rockstar programmer")
});
find returns the first Some(T) that satisfies condition, or returns None. We can use or_else to do action when None is returned. If you'd like to do something with found element, use and_then.