drmason13 / advent_of_code_traits

Minimal, flexible framework for implementing solutions to Advent of Code in Rust
Apache License 2.0
9 stars 3 forks source link

Allow using `self` in Solution implementation #5

Open drmason13 opened 3 years ago

drmason13 commented 3 years ago

All the methods on the traits so far are associated functions.

So essentially the implementing struct is just a marker or container for organising the solutions. It has no use for any data or fields.

I'd like people to experiment with this idea, I have in mind fun implementations of Solution like this:

// from Advent of Code 2019
pub struct IntcodeComputer {
    program: Vec<Instruction>,
    stack: Vec<i32>,
    register: HashMap<Register, i32>,
}

impl Solution<Day2> for IntcodeComputer {
    fn part1(&self) -> u32 {
        // use the intcode computer and access its fields, methods!
        self.program.iter() // ...
    }
}

We could even have mutability.

impl Solution<Day2> for IntcodeComputer {
    fn part1(&mut self) -> u32 {
        // use the intcode computer and mutate it while solving the solution
       self.stack.push(3)
    }
}
drmason13 commented 3 years ago

run might want to ensure each part gets a fresh IntcodeComputer by default.

These signatures are wildly different and incompatible with the current ones, and it won't always make sense to use one or the other.

There might be a need for separate traits, maybe Solution and Solve. I'd like for them to have nice readable names and avoid:

impl SolutionMutSelf<Day2> for IntcodeComputer {

I also wonder if they could blanket impl each other in some way... If something can solve with part1(&self) maybe part1() should just make a Self and then run part1(&self)?