我已经定义了以下数据类型:
data Probability a = PD { mass :: [(a, Ratio Int)] }
Run Code Online (Sandbox Code Playgroud)
现在我想写一下它是一个实例Functor:
collect :: (Eq a, Num b) => [(a, b)] -> [(a, b)]
collect al = map collect' keys where
keys = nub $ map fst al
collect' k = (k, sum (map snd (matches k)))
matches k = filter ((==) k . fst) al
instance (Eq a) => Functor (Probability a) where
fmap f p = PD (collect $ map (first f) (mass p)) …Run Code Online (Sandbox Code Playgroud)