考虑基于2元组的类似lisp的异构“列表”:
let a = (); // ()
let b = (1i32, ('2', ("3", (4u64, ())))); // (1i32 '2' "3", 4u64)
我想像这样连接它们:
let a = (1, ('2', ()));
let b = ("3", (4, ()));
let c = concat(a, b); // (1, ('2', ("3", (4, ()))));
我设法以我认为过于复杂的方式这样做了:
impl<Other> Concat<Other> for () {
type Result = Other;
fn concat(self, other: Other) -> Self::Result {
other
}
}
impl<Head, Tail, Other> Concat<Other> for (Head, Tail)
where Tail: Concat<Other>
{
type Result = (Head, <Tail as Concat<Other>>::Result);
fn concat(self, other: Other) -> Self::Result {
let (head, tail) = self;
(head, tail.concat(other))
}
}
fn main() {
let a = (1, ('2', ()));
let b = ("3", (4, ()));
println!("{:?}", a.concat(b)); // (1, ('2', ("3", (4, ()))));
}
我们可以做得更好吗?如果是这样,怎么样?