簡體   English   中英

如何在Haskell 98中為特定類型的應用程序定義實例?

[英]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專用代碼中,我使用FlexibleInstancesGADTs然后使用

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM