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

map over nested structures #33920

Closed
goretkin opened this issue Nov 22, 2019 · 4 comments
Closed

map over nested structures #33920

goretkin opened this issue Nov 22, 2019 · 4 comments

Comments

@goretkin
Copy link
Contributor

I'd like to write something concise to turn

[(1, 2), ((3, 4), (5, [7, 8]))]

into

[(1.0, 2.0), ((3.0, 4.0), (5.0, [7.0, 8.0]))]

If the structures are "uniformly" nested, one idea from @ssfrr is to e.g. define fmap(f) = x->map(f,x)
then

x = [(1,2), (3,4)]
fmap(fmap(Float64))(x)

You can then use whatever idiom for iterated functions to concisely write deeply but uniformly nested structures.

For non-uniformly nested structures, there's a question about how deep to apply the function. I'm not sure what a good generic API for what I want would be.

Related:
#32081 (comment)
#32796
#20502

@ghost
Copy link

ghost commented Nov 23, 2019

ffmap(f, x::Int) = f(x)
ffmap(f, x::Union{Tuple, Array}) = map(y -> ffmap(f, y), x)

x = [(1, 2), ((3, 4), (5, [7, 8]))]
ffmap(Float64, x)

Like this?

@mcabbott
Copy link
Contributor

Sounds like another reason to want #24990, with which you could write map(map(f, _), xs), I think.

@brenhinkeller
Copy link
Contributor

Between the suggestion above and the zillion underscore proposals and PRs out there, I think we can close this but feel free to undo if anyone disagrees!

@aplavin
Copy link
Contributor

aplavin commented Jan 17, 2023

See Accessors.jl as well: their modify(f, obj, optic) is basically this arbitrarily-nested map.

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

4 participants