[英]Why does `let foo = (fmap . const)` fail with “No instance for (Functor f0) arising from a use of `fmap'”?
[英]Why this structure-preserving “fmap” cannot be acepted in this Functor's class instance?
下面定义的函数mapRightR仅更改映射的设置内容,而不是键,并生成有效的Relation类型。
是否真的不可能使用这个高级函数来定义Functor Relation实例,或者我的实现是错误的。
{-# LANGUAGE GADTs #-}
import Data.Map as M
import Data.Set as S
data Relation a b where
R :: (Ord a, Ord b) => Map a (Set b) -> Relation a b
instance Functor Relation where
fmap f r = mapRightR f r
mapRightR :: Ord b1 => (b2 -> b1) -> Relation a b2 -> Relation a b1
mapRightR f (R r) = R $ M.map (S.map f) r
谢谢, chepner 。
我尝试了另一个关系定义,使用List而不是Set,它可以工作!
data Relation a b where
R :: (Ord a) => Map a [b] -> Relation a b
instance Functor (Relation a) where
fmap f r = mapRightR f r
mapRightR :: (b2 -> b1) -> Relation a b2 -> Relation a b1
mapRightR f (R r) = R $ M.map (L.map f) r
mapRightR
受约束,它不适用于任何类型b
因为fmap
需要:
-- Specialized for f ~ Relation c
fmap :: (a -> b) -> Relation c a -> Relation c b
但
mapRightR :: Ord b => (a -> b) -> Relation c a -> Relation c b
在多个分类而言, Relation c
是不是映射到Hask Hask(这是什么一个endofunctor Functor
类型类的代表)映射Hask的只包含类型的一个子类,而是一个仿函数Ord
实例Hask。 (我认为我正确地表达了这一点;欢迎更正。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.