I have yet another problem with Rust with lifetime inference ...
The following code belongs to a small playground code base for a neural network.
I am mainly using the crate "ndarray" for the matrix stuff.
struct Layer32 {
weights: Array<f32, (Ix, Ix)>,
outputs: Array<f32, Ix>
}
impl NeuralLayer for Layer32 {
type Elem = f32;
fn feed_forward<'a>(
&'a mut self,
input: &[Self::Elem],
activation_fn: &ActivationFn<Self::Elem>
)
-> &'a [Self::Elem] // annotated lifetime!
{
// unimportant impl details ...
self.output_as_slice()
}
}
pub struct ConvolutionalNet32 {
layers: Vec<Layer32>
}
impl NeuralNet for ConvolutionalNet32
{
type Elem = f32;
fn feed<'a, 'b>(&'a mut self, input: &'b [Self::Elem]) -> &'a [Self::Elem] {
{
let mut out = input;
for layer in self.layers.iter_mut() {
out = layer.feed_forward(out, &activation_fn);
}
}
self.layers.last().unwrap().output_as_slice()
}
}
The above code works just fine.
However, I didn't like the ConvolutionalNet32::feed method and thus I experimented a bit to convert it to a (hopefully) equivalent functional method shown below, using only a single fold.
impl NeuralNet for ConvolutionalNet32
{
type Elem = f32;
fn feed<'a, 'b>(&'a mut self, input: &'b [Self::Elem]) -> &'a [Self::Elem] {
self.layers.iter_mut().fold(input, |out, layer| layer.feed_forward(out, &activation_fn))
}
}
The above code is not accepted by the compiler with the following error:
src/prophet/convolutional_net.rs:130:26: 130:30 error: cannot infer an appropriate lifetime due to conflicting requirements [E0495]
src/prophet/convolutional_net.rs:130 self.layers.iter_mut().fold(input, |out, layer| layer.feed_forward(out, &activation_fn))
^~~~
src/prophet/convolutional_net.rs:129:2: 138:3 help: consider using an explicit lifetime parameter as shown: fn feed<'a>(&'a mut self, input: &'a [Self::Elem]) -> &'a [Self::Elem]
src/prophet/convolutional_net.rs:129 fn feed<'a, 'b>(&'a mut self, input: &'b [Self::Elem]) -> &'a [Self::Elem] {
^
Is there a way I can fix this or help the compiler to make it accept the more functional approach?