{-# LANGUAGE FlexibleInstances, FlexibleContexts #-}
在 Haskell 中,我可以做類似的事情
class C a where
c :: a -> a
instance C (f Integer) where
c = id
正如所見, 的實例C
是多態的,但僅在類型構造函數上而不是在類型參數上。這個功能有什麼意義?我從未見過它被使用過,但由於它是允許的,我認為在某些情況下它是有用的。是嗎?
你已經看到它使用了。下面是一些例子:
return :: Monad m => a -> m a
and :: Foldable f => f Bool -> Bool
traverse :: (Applicative f, Traversable t) => (a -> f b) -> t a -> f (t b)
這些中的每一個在具有箭頭類型的類型中都是多態的——分別是m
, f
, 以及兩者f
和t
。如果您必須在實例頭中看到它,那麼將其中任何一個提升到一個類似的實例並不難。例如:
class Bullish a where bull :: a -> Bool
instance Bullish Bool where bull = id
instance Bullish Int where bull = (0/=)
instance Foldable f => Bullish (f Bool) where bull = and
作為術語說明:“類型構造函數”實際上並不是“帶有箭頭類型的類型”的同義詞,其原因基本上與“數據構造函數”與“帶有箭頭類型的值”不相同的原因。
arrow kind not arrow kind
constructor Maybe Bool
not constructor State Int Maybe Char
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句