我正在尝试定义默认方法实现,但前提是类的类型变量派生某些其他类。
我曾尝试使用=>
(我什至正确使用它吗?)创建依赖于类型的实例,但我得到一个“重复的实例声明错误”:(https://repl.it/@solly_ucko/Distributions)
{-# LANGUAGE FlexibleInstances, FunctionalDependencies, MultiParamTypeClasses, InstanceSigs #-}
import Data.Int
import Data.Ratio
import Data.Set
import System.Random
duplicate :: a -> (a, a)
duplicate a = (a, a)
listRange :: Enum a => a -> a -> [a]
listRange a b = [a..b]
class Fractional w => Distribution d v w where
probability :: d v w -> v -> w
probabilityOfRange :: Ord v => d v w -> v -> v -> w
ranges :: (Ord v) => d v w -> Set (v, v)
ranges = (Data.Set.map duplicate) . values
sample :: RandomGen g => d v w -> g -> (v, g)
--sample d g = (scanl1 (+) $ flip Prelude.map $ probability d, g) -- Will need to implement some sort of binary tree, most likely.
sampleIO :: d v w -> IO v
sampleIO = getStdRandom . sample
values :: d v w -> Set v
instance (Ord v, Fractional w) => Distribution d v w where
probability d v = probabilityOfRange d v v
instance Enum v => Distribution d v w where
probabilityOfRange d v1 v2 = sum $ Prelude.map (probability d) [v1..v2]
instance (Enum v, Ord v) => Distribution d v w where
values = fromList . (concatMap $ uncurry listRange) . toList . ranges
然后当我尝试添加真实实例(并注释掉我之前创建的一些“实例”以便编译器可以达到那个点)时,它给了我一个关于冲突实例的错误。
data Empty v w = Empty
instance Distribution Empty v (Ratio Int8) where
sample _ g = (undefined, g)
sampleIO _ = return undefined
probabilityOfRange _ _ _ = 0
values _ = empty
data Singleton v w = Singleton v
instance Distribution Singleton v Integer where
sample (Singleton v) g = (v, g)
sampleIO (Singleton v) = return v
probabilityOfRange (Singleton v1) v2 v3
| v2 <= v1 && v1 <= v3 = 1
| otherwise = 0
data Uniform v w = Uniform (Set v)
澄清一下,我的目标是 for probability
and values
to be defined for all Distributions
,以及 for probabilityOfRange
to be defined for all Distributions
with values deriving Ord
。我还希望在满足其他约束时提供默认值,因为没有它们,合理的默认值(基于其他方法)是不可能的。