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

Possible to match a NamedTuple? #95

Open
fredcallaway opened this issue Sep 29, 2023 · 5 comments
Open

Possible to match a NamedTuple? #95

fredcallaway opened this issue Sep 29, 2023 · 5 comments

Comments

@fredcallaway
Copy link

I didn't see this in the docs so I assume it's not possible. It would be really nice to be able to match NamedTuples, e.g.

@match (;a=1, b=2) begin
    (;a=1, b) => begin
        # I would like to have locals a = 1 and b = 2
    end
end
@xukai92
Copy link

xukai92 commented Oct 11, 2023

had a similar need and found the following work-around works

nt = (; a=1, b=2)
NT = typeof(nt)
@match (; a, b) = nt begin
    NT(1, b) => begin
        # you have access to locals a = 1 and b = 2 here
    end
end

@fredcallaway
Copy link
Author

@xukai92 It looks like this only works for a single type of named tuple. Could be handy, but definitely not a complete solution.

@xukai92
Copy link

xukai92 commented Oct 11, 2023

yeah but NT is constructed programmatically so I guess it's good enough as a work-around.
i guess this logic can be potentially implemented within @match so to achieve the behavior similar to your OP

@fredcallaway
Copy link
Author

fredcallaway commented Oct 12, 2023

I had that thought as well, but I'm not sure how you would handle a case where you want to match on a named tuple that could have different types, e.g.

nt = rand((
    (;a=1, b=2),
    (x = "x", y="z")
))
@match nt begin
    (;a=1, b) => begin
        @show a b
    end
    (;x, y) => begin
        @show x y
    end
end

@xukai92
Copy link

xukai92 commented Oct 12, 2023

i guess in that case you will have to do something even more messy (deconstructing in the match statements)

nts = (
    (; a=1, b=2),
    (; x="x", y="z"),
)
NT1, NT2 = typeof.(nts)

nt = rand(nts)
@match nt begin
    NT1(1, b) => begin
        (; a, b) = nt
        @show a b
    end
    NT2(x, y) => begin
        (; x, y) = nt
        @show x y
    end
end

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

No branches or pull requests

3 participants