![](/img/trans.png)
[英]In Haskell how can I match a type class with an instance of that type class?
[英]How can I define an instance for a specific type application in Haskell 98?
我注意到Data.Set
的測試套件只是真正定義了a ~ Int
理想a ~ Int
Arbitrary Set a
,但要避免GHC特殊~
它使用
instance Enum a => Arbitrary (Set a)
如何確保只使用Arbitrary (Set Int)
實例而不需要任何GHC擴展? 在GHC專用代碼中,我使用FlexibleInstances
或GADTs
然后使用
instance Arbitrary (Set Int)
要么
instance a ~ Int => Arbitrary (Set a)
這可以使用我認為我在Oleg Kiselyov的論文中首次遇到的一個想法,它是Control.Lens.Equality
基礎。
import Data.Functor.Identity
class IsInt a where
fromIntF :: f Int -> f a
instance IsInt Int where
fromIntF fx = fx
toIntF :: IsInt a => g a -> g Int
toIntF = unf . fromIntF . F $ id
newtype F g a b = F {unf :: g b -> a}
fromInt :: IsInt a => Int -> a
fromInt = runIdentity . fromIntF . Identity
toInt :: IsInt a => a -> Int
toInt = runIdentity . toIntF . Identity
現在我可以用了
instance IsInt a => Arbitrary (Set a)
並確信我真的在處理Int
。 為方便起見,我可以使用我需要的任何類來約束IsInt
類,其中Int
是一個實例:
class (Show a, Read a, Integral a, Arbitrary a) => IsInt a where ...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.