Typed Channels
typed_channels.nr168 lines
typed_channels.nr· neuro
// Associated types, one trait with three implementors. Integration example: `type
// Sample` with `Self::Sample` paths, `Channel<Sample = i32>` bounds on a type parameter, a
// trait with default methods, one of them generic, `@derive(Copy)` structs with `&self`
// methods, `Option` and `match`, and `Vec` iteration. A trait without an associated type would have to pick one
// sample type for every instrument, so a thermocouple's `f64`, a tally's `i32` and an
// interlock's `bool` could not share it. `T: Channel<Sample = i32>` puts the answer in the
// bound, so one body serves every counted channel and no float channel.
trait Channel {
type Sample
// Every implementor supplies the reading itself...
func sample(&self) -> Self::Sample
// ...and inherits this, unless it has a better answer.
func channel_id(&self) -> i32 { 0 }
// `U` belongs to the method, not the trait: every implementor inherits this one template,
// and each call picks the type its reading converts to.
func read_as<U>(&self, convert: (Self::Sample) -> U) -> U {
convert(self.sample())
}
}
@derive(Copy, Clone)
struct Thermocouple {
millivolts: f64
}
@derive(Copy, Clone)
struct Tally {
counted: i32
}
@derive(Copy, Clone)
struct Interlock {
latched: bool
}
impl Channel for Thermocouple {
type Sample = f64
// 40 microvolts per degree, the usual type-K approximation.
func sample(&self) -> Self::Sample { self.millivolts * 25.0 }
func channel_id(&self) -> i32 { 1 }
}
impl Channel for Tally {
type Sample = i32
func sample(&self) -> Self::Sample { self.counted }
}
impl Channel for Interlock {
type Sample = bool
func sample(&self) -> Self::Sample { self.latched }
func channel_id(&self) -> i32 { 3 }
}
@derive(Copy, Clone)
struct Cycle {
ticks: i32
}
impl Channel for Cycle {
type Sample = i32
func sample(&self) -> Self::Sample { self.ticks * 2 }
func channel_id(&self) -> i32 { 4 }
}
// One body, every counted channel. The bound is what makes `sample()` typeable here:
// the trait declaration alone says only that `Sample` exists. Passing the thermocouple
// would be rejected: its impl binds `Sample` to f64.
func scaled<T: Channel<Sample = i32>>(source: &T, factor: i32) -> i32 {
source.sample() * factor
}
// The same bound spelled anonymously, for a reader that names its parameter once.
func labelled(source: &impl Channel<Sample = i32>) -> i32 {
source.sample() + source.channel_id()
}
// A generic trait method called through the bound: `U` is inferred here, per call, on top of
// the `Sample` the bound fixed. A trait declaring one is never `dyn Channel`.
func over_limit<T: Channel<Sample = i32>>(source: &T, limit: i32) -> bool {
source.read_as(|n| n > limit)
}
// A drain whose element type is its own associated type: the loop below never names
// `i32`, only `Self::Sample`.
struct Backlog {
pending: i32
}
impl Channel for Backlog {
type Sample = i32
func sample(&self) -> Self::Sample { self.pending }
}
impl Backlog {
func take(&mut self) -> Option<i32> {
if self.pending <= 0 {
return None
}
self.pending -= 1
Some(self.pending + 1)
}
}
func main() -> i32 {
val probe = Thermocouple { millivolts: 2.4 }
val counter = Tally { counted: 17 }
val guard = Interlock { latched: true }
val degrees = probe.sample()
val counted = counter.sample()
val latched = guard.sample()
println("channel {probe.channel_id()} thermocouple -> {degrees:.1} C")
println("channel {counter.channel_id()} tally -> {counted:>4}")
println("channel {guard.channel_id()} interlock -> {latched}")
// The drain: `take()` hands back `Option<Self::Sample>`, unwrapped by `match`
// into a `Vec` of what the impl bound the associated type to.
mut backlog = Backlog { pending: 4 }
mut drained: Vec<i32> = Vec::new()
mut draining = true
while draining {
val next = backlog.take()
match next {
Some(v) => { drained.push(v) }
None => { draining = false }
}
}
mut sum: i32 = 0
for item in drained {
println("drained {item}")
sum += item
}
// The constrained bound: two implementors, one monomorphized body each.
val ticker = Cycle { ticks: 3 }
val scaled_tally = scaled(&counter, 1) // 17
val scaled_cycle = scaled(&ticker, 1) // 6
val marked = labelled(&ticker) // 6 + 4 = 10
println("scaled tally {scaled_tally}, scaled cycle {scaled_cycle}, labelled {marked}")
val hot = probe.read_as(|c| c > 50.0)
val wide_count = counter.read_as::<i64>(|n| n as i64 * 1000000000i64)
println("hot {hot}, wide count {wide_count}, tally over 10: {over_limit(&counter, 10)}")
val holdover = backlog.sample()
val temperature = degrees as i32
val bonus = if latched { 5 } else { 0 }
println("sum {sum}, holdover {holdover}, temperature {temperature}, bonus {bonus}")
val total = sum + holdover + temperature + counted + bonus + scaled_cycle + marked
println("total = {total}")
total
}
neuroc run typed_channels.nr
channel 1 thermocouple -> 60.0 C
channel 0 tally -> 17
channel 3 interlock -> true
drained 4
drained 3
drained 2
drained 1
scaled tally 17, scaled cycle 6, labelled 10
hot true, wide count 17000000000, tally over 10: true
sum 10, holdover 0, temperature 60, bonus 5
total = 108