data Forky a = Tip a | Branch (Forky a) (Forky a)
deriving (Eq, Show)
instance Functor Forky where
-- fmap :: (a -> b) -> Forky a -> Forky b
fmap f (Tip a) = Tip (f a)
fmap f (Branch left right) = Branch (fmap f left) (fmap f right)
instance Applicative Forky where
-- pure :: a -> Forky a
pure a = Tip a
-- (<*>) :: Forky (a -> b) -> Forky a -> Forky b
(<*>) (Branch f g) (Branch left right) =
Branch ((fmap f (Branch left right)) (fmap g (Branch left right)))
一切看起来都不错,直到最后一个功能 (<*>)
错误告诉
? Couldn't match expected type ‘a -> b0’
with actual type ‘Forky (a -> b)’
我该如何解决?谢谢!
在Branch f g
,f
并且g
不是类型的函数a -> b
;它们是类型的子树Forky (a -> b)
。因此,您需要使用<*>
而非fmap
来应用它们。
(Branch fs gs) <*> (Branch left right) = Branch (fs <*> left) (gs <*> right)
此外,您需要考虑在提示中有函数的情况:
(Tip f) <*> (Tip a) = ?
您还应该考虑如果两个参数的形状不同,您会怎么做:
(Tip f) <*> (Branch left right) = ?
(Branch fs gs) <*> (Tip a) = ?
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句