[英]Functor instance of generic functors
data Id a = Id a
data Const a b = Const a
上面的函子实例是
instance Functor Id where
fmap f (Id x ) = Id (f x )
instance Functor (Const a) where
fmap f (Const x ) = Const x
f
以某种方式不适用于const
,则const (fx)
我困惑,因为至少它涉及一个变量。
假设我们有f :: Bool -> Int
和
x :: Const String Bool
x = Const "some string here"
现在, fmap fx
必须具有Const String Int
类型,其结果y
的唯一合理选择是
y :: Const String Int
y = Const "some string here"
请注意x
和y
如何大致相同的值,但是它们属于不同的类型。 此外,为了计算y
我们不必以任何方式使用f
,因为x
里面没有任何Bool
,而y
里面没有任何Int
。 f
则无关紧要。
需要注意的是型Const ab
同构于a
,无论何种类型b
是。 这就是为什么它被命名为Const
的原因:它实际上并没有使用第二个参数。 它的第二个参数仍然很重要,因为它使Const ab
和Const a b'
成为不同的类型,即使它们都与a
同构。
Const
实例仅忽略f
函数,并且不更改其值。 Id
实例将f
函数应用于其值,并返回具有新值的新Id
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.