我怎样才能做到这一点?
data SumTerm =
St_TotalSum TotalSum
|St_SumInS SumInS
|St_SumInT SumInT
|St_HTerm HTerm
data Monomial = Monomial {
mSumTerm :: SumTerm,
xPower :: Int,
yPower :: Int,
coefficient :: Int
}
newtype Polynomial = Polynomial [ Monomial ]
{- Ok, here I'm lost, VERY lost -}
toMonomial :: (forall {- a which can be in a SumTerm constructor -} )
=> a -> SumTerm
toMonomial sum_term = ....
我当然想到了这个解决方案:
class ToSumTerm a where
toSumTerm :: a -> SumTerm
instance ToSumTerm TotalSum where
toSumTerm total_sum = St_TotalSum total_sum
instance ToSumTerm SumInS where
toSumTerm sum_in_s = St_SumInS sum_in_s
...
toMonomial :: ToSumTerm a => a -> Monomial
toMonomial x = Monomial ( toSumTerm a ) 0 0 1
但它不会自动扩展到 SumTerm 的构造函数。有没有一种简单的方法不必手工编写实例,甚至更好,如果可能的话,甚至不用编写类ToSumTerm
?换句话说,是否有一些语法允许废弃样板实例定义(或达到等效效果)?如果有解决方案,它当然可以暗示任何 GHC 扩展,例如 GADT。