1abstract type Shape end
2
3struct Circle <: Shape
4 radius::Float64
5end
6
7struct Rectangle <: Shape
8 width::Float64
9 height::Float64
10end
11
12struct Triangle <: Shape
13 a::Float64
14 b::Float64
15 c::Float64
16end
17
18area(c::Circle) = pi * c.radius^2
19area(r::Rectangle) = r.width * r.height
20function area(t::Triangle)
21 s = perimeter(t) / 2
22 sqrt(s * (s - t.a) * (s - t.b) * (s - t.c))
23end
24
25perimeter(c::Circle) = 2 * pi * c.radius
26perimeter(r::Rectangle) = 2 * (r.width + r.height)
27perimeter(t::Triangle) = t.a + t.b + t.c
28
29function scale(c::Circle, factor::Float64)
30 Circle(c.radius * factor)
31end
32
33function scale(r::Rectangle, factor::Float64)
34 Rectangle(r.width * factor, r.height * factor)
35end
36
37function total_area(shapes::Vector{<:Shape})
38 sum(area.(shapes))
39end
40
41function largest(shapes::Vector{<:Shape})
42 areas = area.(shapes)
43 idx = argmax(areas)
44 shapes[idx]
45end
46
47function filter_by_area(
48 shapes::Vector{<:Shape},
49 min_area::Float64,
50 max_area::Float64
51)
52 [s for s in shapes if min_area <= area(s) <= max_area]
53end
54
55function stats(shapes::Vector{<:Shape})
56 areas = area.(shapes)
57 Dict(
58 "count" => length(shapes),
59 "total_area" => sum(areas),
60 "mean_area" => sum(areas) / length(areas),
61 "min_area" => minimum(areas),
62 "max_area" => maximum(areas),
63 "std_area" => std(areas)
64 )
65end
66
67function transform_all(
68 shapes::Vector{<:Shape},
69 f::Function
70)
71 [f(s) for s in shapes]
72end