1

Note: I may not need to add Scalar to Eq, although it should solve the problem if I could figure out how to do just that.

So I'm trying to add some functionality to the ForceLayout module. Adding mass to Particles like so:

data Particle v = Particle { 
                         _pos   :: Point v
                       , _vel   :: v
                       , _force :: v
                       , _mass :: Scalar v
                       }
    deriving (Eq, Show)

But Scalar is not in Eq or Show! So this wont compile. Mass should be a scalar "compatible" with the other vectors though. How can I reconcile this? I don't understand type families sufficiently to analyse this situation. I've tried but they are mighty hard to grasp. Not sure if adding Scalar to Eq is necessary or possible.

4

1 に答える 1

5

質量フィールドを表示する場合、表示インスタンスは次のようにする必要があります。

instance (Show v, Show (Point v), Show (Scalar v)) => Show (Particle v) where

おそらく、GHC がこれを解決しないという事実は、バグか、少なくとも欠落している機能です。幸いなことに、いくつかの拡張機能を使用すると、コンテキストを自分で与えることができます。

{-# LANGUAGE StandaloneDeriving, TypeFamilies,
    FlexibleContexts, UndecidableInstances #-}
{- ... -}

deriving instance (Show v, Show (Point v), Show (Scalar v)) => Show (Particle v)

これは、GHC ユーザー ガイドで説明されている「スタンドアロンの派生宣言」であり、ここでの目的は、基本的に、GHC が通常うまくいかないコンテキストを指定できるようにすることです。

これでうまくいくはずです。UndecidableInstances については少し心配です。このインスタンスが循環するようにPointandのインスタンスを定義することは可能であるように思われるからです。Scalarおそらく大丈夫です。

于 2012-06-07T17:34:21.360 に答える