Copying my prior-art comment from Reddit:
Haskell supports a form of generics that allows (with some effort on the part of the trait author, like this RFC):
class Serialize a where
put :: a -> [Bit]
default put :: (Generic a, GSerialize (Rep a)) => a -> [Bit]
put a = gput (from a)
get :: [Bit] -> (a, [Bit])
default get :: (Generic a, GSerialize (Rep a)) => [Bit] -> (a, [Bit])
get xs = (to x, xs')
where (x, xs') = gget xs
-- ...stuff...
data UserTree a = Node a (UserTree a) (UserTree a) | Leaf
deriving (Generic, Show)
instance (Serialize a) => Serialize (UserTree a)
which ‘derives’ an impl of the custom Serialize
trait for the custom UserTree
type. (In Rust terminology.)