我能够通过以下方式将Functor的定义从类别理论映射到Haskell的定义:因为Hask类型的对象,仿函数F
a的地图映射Hask到新类型F a,粗略地说,在它之前加上"F".a -> b的Hask新态射F a -> F b使用fmap :: (a -> b) -> (f a -> f b).到现在为止还挺好.现在我到了Applicative,在教科书中找不到任何提及这样的概念.通过查看它增加了Functor,ap :: f (a -> b) -> f a -> f b我试着拿出我自己的定义.
首先,我注意到,因为(->)它也是一种类型,态射Hask也是它的对象.鉴于此,我提出了一个建议,即应用仿函数是一个仿函数,它也可以将"箭头" - 源类别的对象映射到目标类型的态射.
这是正确的直觉吗?你能提供更正式和严谨的定义吗?
对于不确定性传播Approximate类型,我想要Functor通过实例Monad.然而,这不起作用,因为我需要在包含的类型上使用向量空间结构,因此它实际上必须是类的受限版本.由于仍有似乎并不为那些标准库(或者是那里?请点我.还有rmonad,但它使用*,而不是Constraint作为上下文样,这似乎只是过时的我),我写我自己的版本的暂时的.
这一切都很容易 Functor
class CFunctor f where
type CFunctorCtxt f a :: Constraint
cfmap :: (CFunctorCtxt f a, CFunctorCtxt f b) => (a -> b) -> f a -> f b
instance CFunctor Approximate where
type CFunctorCtxt Approximate a = FScalarBasisSpace a
f `cfmap` Approximate v us = Approximate v' us'
where v' = f v
us' = ...
Run Code Online (Sandbox Code Playgroud)
但是直接翻译Applicative,就像
class CFunctor …Run Code Online (Sandbox Code Playgroud) 适用于Monoidal Functor:
mappend :: f -> f -> f
$ :: (a -> b) -> a -> b
<*> :: f(a -> b) -> f a -> f b
Run Code Online (Sandbox Code Playgroud)
但是我没有在应用类型类的定义中看到有关Monoid的任何参考,你能告诉我为什么吗?
定义:
class Functor f => Applicative (f :: * -> *) where
pure :: a -> f a
(<*>) :: f (a -> b) -> f a -> f b
GHC.Base.liftA2 :: (a -> b -> c) -> f a -> f b -> f c
(*>) :: f a …Run Code Online (Sandbox Code Playgroud) 不久前,我已经学会了Monoidal作为一种替代方式来表示Applicative。Typeclassopedia上有一个有趣的问题:
- (棘手)证明给定你在第一个练习中的实现[
pure并(<*>)用unit和(**)和相反的方式写下来],通常的Applicative规律和上述Monoidal规律是等价的。
以下是这些课程和法律:
-- A note from https://wiki.haskell.org/Typeclassopedia#Alternative_formulation:
-- In this and the following laws, ? refers to isomorphism rather than equality.
-- In particular we consider (x,()) ? x ? ((),x) and ((x,y),z) ? (x,(y,z)).
-- Monoidal.
class Functor f => Monoidal f where
unit :: f ()
(**) :: f a -> f b -> f (a,b)
-- unit ** …Run Code Online (Sandbox Code Playgroud)