|
| 1 | +# [Homework 7: Creating world in 3 days/steps](@id hw07) |
| 2 | + |
| 3 | +## How to submit |
| 4 | +Put all the code of inside `hw.jl`. Zip only this file (not its parent folder) and upload it to BRUTE. You should assume that only |
| 5 | +```julia |
| 6 | +using Ecosystem |
| 7 | +``` |
| 8 | +will be put before your file is executed, but do not include them in your solution. The version of `Ecosystem` pkg should be the same as in [HW4](@ref hw4). |
| 9 | + |
| 10 | +```@raw html |
| 11 | +<div class="admonition is-category-homework"> |
| 12 | +<header class="admonition-header">Homework (2 points)</header> |
| 13 | +<div class="admonition-body"> |
| 14 | +``` |
| 15 | +Create a macro `@ecosystem` that should be able to define a world given a list of statements `@add # $species ${optional:sex}` |
| 16 | +```julia |
| 17 | +world = @ecosystem begin |
| 18 | + @add 10 Sheep female # adds 10 female sheep |
| 19 | + @add 2 Sheep male # adds 2 male sheep |
| 20 | + @add 100 Grass # adds 100 pieces of fully grown grass |
| 21 | + @add 3 Wolf # adds 5 wolf with random sex |
| 22 | +end |
| 23 | +``` |
| 24 | +`@add` should not be treated as a macro, but rather just as a syntax, that can be easily matched. |
| 25 | + |
| 26 | +As this is not a small task let's break it into 3 steps. (These intemediate steps will also be checked in BRUTE.) |
| 27 | +1. Define method `default_config(::Type{T})` for each `T` in `Grass, Wolf,...`, which returns a named tuple of default parameters for that particular agent (you can choose the default values however you like). |
| 28 | +2. Define method `_add_agents(max_id, count::Int, species::Type{<:Species})` and `_add_agents(max_id, count::Int, species::Type{<:AnimalSpecies}, sex::Sex)` that return an array of `count` agents of species `species` with `id` going from `max_id+1` to `max_id+count`. Default parameters should be constructed with `default_config`. Make sure you can handle even animals with random sex (`@add 3 Wolf`). |
| 29 | +3. Define the underlying function `_ecosystem(ex)`, which parses the block expression and creates a piece of code that constructs the world. |
| 30 | + |
| 31 | +You can test the macro (more precisely the `_ecosystem` function) with the following expression |
| 32 | +```julia |
| 33 | +ex = :(begin |
| 34 | + @add 10 Sheep female |
| 35 | + @add 2 Sheep male |
| 36 | + @add 100 Grass |
| 37 | + @add 3 Wolf |
| 38 | +end) |
| 39 | +genex = _ecosystem(ex) |
| 40 | +world = eval(genex) |
| 41 | +``` |
| 42 | + |
| 43 | +```@raw html |
| 44 | +</div></div> |
| 45 | +<details class = "solution-body" hidden> |
| 46 | +<summary class = "solution-header">Solution:</summary><p> |
| 47 | +``` |
| 48 | + |
| 49 | +Nothing to see here |
| 50 | + |
| 51 | +```@raw html |
| 52 | +</p></details> |
| 53 | +``` |
0 commit comments