Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Tuples and Outer #140

Open
lesobrod opened this issue Aug 9, 2023 · 1 comment
Open

Tuples and Outer #140

lesobrod opened this issue Aug 9, 2023 · 1 comment

Comments

@lesobrod
Copy link

lesobrod commented Aug 9, 2023

Hi! I"d like to reproduce next Mathematica functions on Julia:
Tuples and
Outer
Is it possible with your package, or may be I can add to it?

@FedericoStra
Copy link

They can be both implemented with Iterators.product:

tuples(iter, n) = Iterators.product(ntuple(_ -> iter, n)...)
outer(f, iters...) = Iterators.map(args -> f(args...), Iterators.product(iters...))

Example usage:

julia> for t in tuples(1:3, 2) print(t, "  ") end
(1, 1)  (2, 1)  (3, 1)  (1, 2)  (2, 2)  (3, 2)  (1, 3)  (2, 3)  (3, 3)

julia> for o in outer((x,y)->10x+y, 1:2, 4:5) print(o, " ") end
14 24 15 25

Notice that in some cases it can be more convenient to use generators directly

julia> for t in ((x,y) for x in 1:3, y in 1:3) print(t, "  ") end
(1, 1)  (2, 1)  (3, 1)  (1, 2)  (2, 2)  (3, 2)  (1, 3)  (2, 3)  (3, 3)

julia> [(x,y) for x in 1:3, y in 1:3]
3×3 Matrix{Tuple{Int64, Int64}}:
 (1, 1)  (1, 2)  (1, 3)
 (2, 1)  (2, 2)  (2, 3)
 (3, 1)  (3, 2)  (3, 3)

julia> for o in (10x+y for x in 1:2, y in 4:5) print(o, " ") end
14 24 15 25

julia> [10x+y for x in 1:2, y in 4:5]
2×2 Matrix{Int64}:
 14  15
 24  25

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants