This page is located in archive. Go to the latest version of this course pages. Go the latest version of this page.

Homework 02 - Counting Agents

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 Agents that are counted. Below we demonstrate how to implement agent_count for an arbitrary number of Agents. 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)
            d[n] = agent_count(a)
        return d
    foldl(op, w.agents |> values |> collect, init=Dict{Symbol,Real}())

courses/b0m36spj/tutorials/hw02.txt · Last modified: 2021/10/19 12:11 by heimnikl