嗨,我是Haskell的新手,主要是从LYAH和Hutton读书.最近我遇到了这个状态monad的Functor实例的片段,表示为:
instance Functor (State st) where
fmap f m = State $ \st -> let (a, s) = runState m st in (f a, s)
Run Code Online (Sandbox Code Playgroud)
这可以简化为:
instance Functor (State st) where
fmap f m = State $ (\(a,s) -> (f a,s)) . runState m
Run Code Online (Sandbox Code Playgroud)
谁能解释这种减少背后的工作流程?
关于如何学习这种减少技术,还有哪些好的资源/建议?
我有一个树的以下定义
data Tree a = Leaf a
| Node [Tree a]
deriving (Show)
Run Code Online (Sandbox Code Playgroud)
以及可折叠的以下实例:
instance Foldable (Tree) where
foldMap f (Leaf t) = (f t)
foldMap f (Node t) = (foldMap `mappend` (foldMap f) t)
Run Code Online (Sandbox Code Playgroud)
这段代码引发了我的错误
Couldn't match type `a' with `Tree a'
`a' is a rigid type variable bound by
the type signature for
foldMap :: Monoid m => (a -> m) -> Tree a -> m
at trees.hs:8:5
Expected type: [a]
Actual type: [Tree a]
Run Code Online (Sandbox Code Playgroud)
如何在Tree a类型的实例声明中而不是?