我试图通过在Javascript中实现他们的函数实例来提高我对Applicatives和Monads的理解.我对Haskell的了解有限,我希望我的问题有道理.
下面是我的实现fmap,<*>以及>>=为Functor,Applicative并Monad在Javascript类型类:
const fmap = f => g => x => f(g(x)); // B combinator
const apply = f => g => x => f(x) (g(x)); // S combinator
const bind = f => g => x => g(f(x)) (x); // ?
Run Code Online (Sandbox Code Playgroud)
我不确定bindHaskell实现的正确翻译是否正确:
(>>=) :: (r -> a) -> (a -> (r -> b)) -> r -> b
instance Monad ((->) r) …Run Code Online (Sandbox Code Playgroud) 假设我有一个对类型:
data Pair a = Pair a a
Run Code Online (Sandbox Code Playgroud)
为它编写monad实例的正确方法是什么?我的想法大致是这样的:
instance Semigroup a => Semigroup (Pair a) where
Pair a1 a2 <> Pair b1 b2 = Pair (a1 <> b1)(a2 <> b2)
instance Monad Pair where
return = pure
(Pair a b) >>= f = f a <> f b
Run Code Online (Sandbox Code Playgroud)
这是对的吗?如果是这样,那么在对中指定b型中的b类型是一个半群?