{-# LANGUAGE FlexibleInstances, FlexibleContexts #-}
在 Haskell 中,我可以做類似的事情
class C a where
c :: a -> a
instance C (f Integer) where
c = id
正如所見, 的實體C是多型的,但僅在型別建構式上而不是在型別引數上。這個功能有什么意義?我從未見過它被使用過,但由于它是允許的,我認為在某些情況下它是有用的。是嗎?
uj5u.com熱心網友回復:
你已經看到它使用了。下面是一些例子:
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/370705.html
