Logo

Programming-Idioms

  • PHP
  • Python
  • Scheme

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.

for item in items:
    if item == 'baz':
        print('found it')
        break
else:
    print('never found it')
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";
    }
);
(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.

New implementation...