[英]Using functors/applicatives on custom data types with multiple type classes?
[英]Functors and Applicatives for types of kind (* -> *) -> *
我遇到了一種情況,我的代碼將從使用Functor
和類似Applicative
的抽象中受益,但對於類型(* -> *) -> *
。 定義更高級的仿函數可以使用這樣的RankNTypes
來完成
class HFunctor f where
hfmap :: (forall x. a x -> b x) -> f a -> f b
但是更高版本的Applicative
有點棘手。 這是我能想到的最好的:
class HFunctor f => HApplicative f where
hpure :: (forall x. a x) -> f a
(<**>) :: f (a :-> b) -> f a -> f b
newtype (:->) a b x = HFunc (a x -> b x)
infixr 5 :->
我們需要:->
包裝器類型,以便具有類型* -> *
函數,但這不能讓我們很好地鏈接函數應用程序,就像我們可以使用<$>
和<*>
使用普通的Applicatives。 我可以用幫手來管理
liftHA2 :: HApplicative f => (forall x. a x -> b x -> c x) -> f a -> f b -> f c
liftHA2 f fa fb = hpure (fun2 f) <**> fa <**> fb where
fun2 = HFunc . (HFunc .)
但是有一個通用的方法可以“解除”任何arity的功能。
一些簡單的例子如何使用上述實例:
data Example f = Example (f Int) (f String)
instance HFunctor Example where
hfmap f (Example i s) = Example (f i) (f s)
instance HApplicative Example where
hpure a = Example a a
Example (HFunc fi) (HFunc fs) <**> Example i s = Example (fi i) (fs s)
e :: Example []
e = Example [1,2,3] ["foo", "bar"]
e' :: Example ((,) Int)
e' = hfmap (length &&& head) e -- Example (3,1) (2, "foo")
e'' :: Example []
e'' = liftHA2 (++) e e -- Example [1,2,3,1,2,3] ["foo", "bar", "foo", "bar"]
所以,我的問題是:上面提到的類型類是什么,它們是否已經被一些庫中的hackage提供了? 谷歌搜索,我想出了Functor2
的linear-maps
和HFunctor
在multi-rec
但同樣沒有正是我需要的。
另外,是否有一些方法可以編寫HApplicative
而不使用:->
包裝器或其他一些方法來使函數提升更容易?
我傾向於認為的HFunctor是(* -> *) -> * -> *
- 即仿函數上的合法函子。 這與你想到的不同。
以下是如何定義它,以及應用程序的“monoidal”版本。
type Nat f g = forall a. f a -> g a
class HFunctor (f :: (* -> *) -> * -> *) where
hfmap :: (Nat g h) -> Nat (f g) (f h)
data Prod f g a = Prod (f a) (g a)
class HFunctor f => HApplicative f where
hpure :: Nat g (f g)
htensor :: Nat (Prod (f g) (f h)) (f (Prod g h))
我稍后會嘗試更新一些關於這是什么以及如何使用它的想法。
我意識到,這並不是你所要求的,但我的靈感來自你的帖子。
我也對你的具體用例感興趣。
關於你的兩個具體問題A)你所描述的HFunctor之前已經在不同場合進行了描述,我特別想到Gibbons,但我不知道它是否打包過。 我當然沒有見過申請人。 B)我認為你堅持使用包裝器,因為我們不能部分應用類型同義詞。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.