Skip to content

Instantly share code, notes, and snippets.

@Summertime
Last active November 17, 2018 07:28
Show Gist options
  • Save Summertime/66ee8bcabb040a6dd8d694064d1a2f87 to your computer and use it in GitHub Desktop.
Save Summertime/66ee8bcabb040a6dd8d694064d1a2f87 to your computer and use it in GitHub Desktop.

Python 3 vs Perl 6

There are more ways to do it in perl6, so thats bad!

word-dash-number iteration

# Python
map('link-{}'.format, itertools.count())
# or
(f'link-{n}' for n in itertools.count())
# or
('link-%d' % n for n in itertools.count())
# or
('link-' + str(n) for n in itertools.count())
# or
('link-{}'.format(n) for n in itertools.count())
# Perl6
'link-0' .. *;
# or
'link-0' .. Inf;

Chaining known iterables

# Python
[*a, *b]
# or
list(itertools.chain(a, b))
# Perl6
|@a, |@b;

Chaining unknown iterables

# Python
itertools.chain.from_iterable(a)
# Perl6
map |*, @a;

Fibonacci

# Python
def fibonacci():
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b
# Perl6
0, 1, *+* ... *;

Word-number iteration with set filter

# Python
# what was submitted ;;
next(name for name in map('tag{}'.format, itertools.count(1)) if name not in existing_tags))
# my versions
next(f'tag{i}' for i in itertools.count(1) if f'tag{i}' not in existing_tags)
# or
next(name for i in itertools.count(1) if (name := f'tag{i}') not in existing_tags)
# using toolz
next(
    pipe(
        itertools.count(1),
        map( lambda x: f'tag{x}' ),
        filter( lambda x: x not in existing_tags ),
    )
)
# Perl6
first *  $existing_tags,  map 'tag' ~ *,  1..*;
# or
(1..*).map( 'tag' ~ * ).first( *  $existing_tags );
# or
1..*
    ==> map 'tag' ~ *
    ==> first *  $existing_tags;

# Python
# Perl6
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment