从面向对象编程来看,这段代码对我来说很陌生。
我不理解为什么runIdentity
的类型是一个函数:
runIdentity :: Identity a -> a
? 我指定它应该是runIdentity :: a
newtype Identity a = Identity {runIdentity :: a} deriving Show
instance Monad Identity where
return = Identity
Identity x >>= k = k x
instance Functor Identity where
fmap f (Identity x) = Identity (f x)
instance Applicative Identity where
pure = Identity
Identity f <*> Identity v = Identity (f v)
wrapNsucc :: Integer -> Identity Integer
wrapNsucc = Identity . succ
调用runIdentity
:
runIdentity $ wrapNsucc 5 -- 输出6
class C {int x;}; C i;
现在i.x
是一个int
,同样地,如果你有i :: Identity Int
那么runIdentity i
就是一个Int
。所以如果i
是一个Identity Int
,runIdentity i
是一个Int
,那么runIdentity
是什么? - user253751