Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!

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.

  found = .false.
  do i=1,size(items)
    if (items(i) == "asdf") then
      found = .true.
      exit
    end if
  end do
  if (.not. found) call do_something
(if (seq (filter odd? my-col))
  "contains odds"
  "no odds found")
#include <list>
bool found = false;
for (const auto item : items) {
  if (item == "baz") {
    baz();
    found = true;
    break;
  }
}
if (!found) {
  DoSomethingElse();
}
#include <algorithm>
if (std::any_of(items.begin(), items.end(), condition))
    baz();
else
    DoSomethingElse();
using System.Linq;
if (!items.Any(i => MatchesCondition(i)))
{
	DoSomethingElse();
}
print(items.any((element) => element == "baz")
    ? "found it"
    : "did not find it");
for _, item := range items {
    if item == "baz" {
        fmt.Println("found it")
        goto exit
    }
}
{
    fmt.Println("not found")
}
exit:
println(items.any { it == "baz" } ? 'found' : 'not found')
const found = items.some(condition);

if (!found) doSomethingElse();
Predicate<Item> condition;
items.stream()
	.filter(condition)
	.findFirst()
	.ifPresentOrElse(
		item -> doSomething(i),
		() -> doSomethingElse());
boolean b = false;
for (int i = 0; i<items.length; i++) {
	if (items[i] == something) {
		doSomething();
		b = true;
	}
}
if (!b)
	doSomethingElse();
items.find { it == "baz" }
  ?.let { println("found it") }
  ?: println("never found it")
if(items.any { it == "baz" })
  println("found it")
else 
  println("never found it")
(loop for item in items
      when (check-match item) return (do-something item)
      finally (return (do-something-else))
local function list_cond(t,cond)
 for _,v in ipairs(t) do
  if cond(v)==true then return true end
 end
 return false
end
if list_cond(items,function(x) return x==0 end) then
 print("did find 0")
else
 print("didn't find 0")
end
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";
    }
);
Found := False;
for Item in Items do
begin
  if Item.MatchesCondition then
  begin
    Found := True;
    Break;
  end;
end;
if not Found then 
  DoSomethingElse;
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";
}
for item in items:
    if item == 'baz':
        print('found it')
        break
else:
    print('never found it')
items = ['foo', 'bar', 'baz', 'qux']
puts items.any?("baz") ? "found it" : "never found it"
items
    .iter()
    .find(|&&item| item == "rockstar programmer")
    .or_else(|| {
        println!("NotFound");
        Some(&"rockstar programmer")
    });
if 'search: loop {
    for i in items {
        if i == &"qux" {
            println!("found it");
            break 'search false;
        }
    }
    break 'search true
} {
    println!("not found!");
}
'label: {
	for &item in items {
		if item == "baz" {
			println!("found");
			break 'label;
		}
	}
	println!("not found");
}
let mut found = false;
for item in items {
    if item == &"baz" {
        println!("found it");
        found = true;
        break;
    }
}
if !found {
    println!("never found it");
}
if let None = items.iter().find(|&&item| item == "rockstar programmer") {
        println!("NotFound");
    };

New implementation...
< >
Ruien