The implementation of agent_count
is split into multiple parts via dispatch.
First, we can implement the methods for Plant
and Animal
as described in the homework text.
Second, the agent count of a vector is another method which can be conveniently implemented with
sum(f::Function,v::Vector)
. This method applies f
to each element in v
and sums the result.
Using agent_count
as the function that is passed to sum
will result in the application of the methods
for Plant
and Animal
which we implemented already.
Finally, we need a method for World
. We have seen many different ways of doing this in your homeworks.
Some of them hardcoded the types of Agent
s that are counted.
Below we demonstrate how to implement agent_count
for an arbitrary number of Agent
s.
Note that the solution uses foldl
but you can just as well do it with a for loop.
agent_count(p::Plant) = size(p)/max_size(p) agent_count(::Animal) = 1 agent_count(as::Vector{<:Agent}) = sum(agent_count,as) function agent_count(w::World) function op(d::Dict,a::A) where A<:Agent n = nameof(A) if n in keys(d) d[n] += agent_count(a) else d[n] = agent_count(a) end return d end foldl(op, w.agents |> values |> collect, init=Dict{Symbol,Real}()) end