StopIteration analog in Julia

Hi Everyone,
I recently wrote this code in python (I’m enjoying learning how to write code in a functional manner) that returns whatever numbers are at the end of a string (fails out if there aren’t any).

from functools import reduce
from operator import add


def get_num_from_end_of_string(string: str) -> int:
    backward_nums = list(filter(picky_digit, reversed(string)))
    return int(reduce(add, reversed(backward_nums)))


def picky_digit(s: str) -> bool:
    if s.isdigit():
        return True
    else:
        raise StopIteration

And I’d like to learn how to write something similar in Julia. In a looped version of this, I would put a break after we stop getting digits. In Python I mimic the break with a StopIteration. How can I do this in Julia?
(Any suggestions to make the Python version better are also welcome)

Take a look at Writing Iterators in Julia 0.7 and Interfaces · The Julia Language.

1 Like

StopIteration analog in Julia is return-nothing-from-iterate. See the link above formore info.

You can also use IterTools.takewhile (itertools.takewhile in Python) to directly do what you want.

I strongly suggest to not use function like picky_digit. The predicate function you passed to filter is better not to have any visible side-effects. This applies to coding in Julia and I guess in any languages.

2 Likes