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

Support a dispatch macro to avoid the need of branching #52

Closed
Tortar opened this issue Apr 24, 2024 · 0 comments · Fixed by #53
Closed

Support a dispatch macro to avoid the need of branching #52

Tortar opened this issue Apr 24, 2024 · 0 comments · Fixed by #53

Comments

@Tortar
Copy link
Member

Tortar commented Apr 24, 2024

E.g. say we have

using MixedStructTypes

abstract type AbstractShape end

@sum_structs Shape <: AbstractShape begin
    @kwdef struct Square
        side::Float64 = rand()
    end   
    @kwdef struct Rectangle
        width::Float64 = rand()
        height::Float64 = rand()
    end
    @kwdef struct Triangle
        base::Float64 = rand()
        height::Float64 = rand()
    end
    @kwdef struct Circle
        radius::Float64 = rand()
    end
end

currently we can define an area function like so:

function area(sh)
    if kindof(sh) === :Square
        area_square(sh)
    elseif kindof(sh) === :Rectangle
        area_rectangle(sh)
    elseif kindof(sh) === :Triangle
        area_triangle(sh)
    elseif kindof(sh) === :Circle
        area_circle(sh)
    else
        area_default(sh)
    end
end
   
area_square(s) = s.side * s.side
area_rectangle(r) = r.width * r.height
area_triangle(t) = 1.0/2.0 * t.base * t.height
area_circle(c) = π * c.radius^2
area_default(::AbstractShape) = 0.0

but actually we can generate all of this. So probably something like this should suffice

@dispatch area(s::Square) = s.side * s.side
@dispatch area(r::Rectangle) = r.width * r.height
@dispatch area(t::Triangle) = 1.0/2.0 * t.base * t.height
@dispatch area(c::Circle) = π * c.radius^2
@dispatch area(::AbstractShape) = 0.0
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

Successfully merging a pull request may close this issue.

1 participant