From 7fc6b55b5165276e3019271ac3483dcd279c6ff2 Mon Sep 17 00:00:00 2001 From: parrrate Date: Thu, 9 Apr 2026 12:56:14 +0000 Subject: [PATCH] `AnyStr` example --- src/exercises/anystr.md | 53 +++++++++++++++++++++++++++++++++++++++++ src/topics.md | 3 +-- 2 files changed, 54 insertions(+), 2 deletions(-) diff --git a/src/exercises/anystr.md b/src/exercises/anystr.md index 645e7b1..f102d76 100644 --- a/src/exercises/anystr.md +++ b/src/exercises/anystr.md @@ -3,3 +3,56 @@ Create something similar to [Python's `typing.AnyStr`]. [Python's `typing.AnyStr`]: https://docs.python.org/3/library/typing.html#typing.AnyStr + +Example of what it may allow (solution isn't required to pass these tests, but should): +```rust +# pub trait Equivalent { +# type T; +# fn st_ref(&self) -> &Self::T; +# fn st_mut(&mut self) -> &mut Self::T; +# fn st_move(self) -> Self::T; +# fn ts_ref(t: &Self::T) -> &Self; +# fn ts_mut(t: &mut Self::T) -> &mut Self; +# fn ts_move(t: Self::T) -> Self; +# } +# pub trait Accepts { +# type Output; +# type E; +# fn accept(self) -> Self::Output where Self::E: Equivalent; +# } +# pub trait AnyStr{fn provide+Accepts,E=Self,Output=Output>,Output>(accepts:A)->Output;} +# impl Equivalent for T { +# type T = T; +# fn st_ref(&self) -> &Self::T { self } +# fn st_mut(&mut self) -> &mut Self::T { self } +# fn st_move(self) -> Self::T { self } +# fn ts_ref(t: &Self::T) -> &Self { t } +# fn ts_mut(t: &mut Self::T) -> &mut Self { t } +# fn ts_move(t: Self::T) -> Self { t } +# } +# impl AnyStr for String { +# fn provide+Accepts,E=Self,Output=Output>,Output>(accepts:A)->Output{>::accept(accepts)} +# } +# impl AnyStr for Vec { +# fn provide+Accepts,E=Self,Output=Output>,Output>(accepts:A)->Output{>>::accept(accepts)} +# } +# pub struct Concat(E, E); +# impl Accepts for Concat { +# type Output = E; +# type E = E; +# fn accept(self) -> Self::Output where E: Equivalent { E::ts_move(self.0.st_move() + self.1.st_ref()) } +# } +# impl Accepts> for Concat { +# type Output = E; +# type E = E; +# fn accept(self) -> Self::Output where E: Equivalent> { +# let mut a: Vec = self.0.st_move(); +# let mut b: Vec = self.1.st_move(); +# a.append(&mut b); +# E::ts_move(a) +# } +# } +# pub fn concat(a: T, b: T) -> T { T::provide(Concat(a, b)) } +assert_eq!(concat("ab".to_string(), "cd".to_string()), "abcd".to_string()); +assert_eq!(concat(vec![2u8, 3u8], vec![5u8, 7u8]), vec![2u8, 3u8, 5u8, 7u8]); +``` diff --git a/src/topics.md b/src/topics.md index be56b31..85d9296 100644 --- a/src/topics.md +++ b/src/topics.md @@ -6,8 +6,7 @@ Rows are ordered based on estimated difficulty. |------------------------|--------------------|--------------| | [explicit lifetimes] | [`Fn`?] | [`Duration`] | | [extracting lifetimes] | [exclusive traits] | [`RcChars`] | -| [composition] | [`AnyStr`] | | -| | [merging traits] | | +| [composition] | [merging traits] | [`AnyStr`] | [explicit lifetimes]: ./exercises/refbind.md