cod*_*dde 0 haskell functional-programming function list functor
我有这个蹩脚的尝试:
fmap2 :: (Functor f, Functor g) => (a -> b) -> f (g a) -> f (g b)
fmap2 f f2 = (fmap2 f . fmap f2)
Run Code Online (Sandbox Code Playgroud)
它应该像这样工作:
fmap2 negate [[1,2], [3]] -- Returns [[-1,-2],[-3]]
fmap2 head [Just "abc",Nothing,Just "def"] -- Returns [Just 'a',Nothing,Just 'e']
Run Code Online (Sandbox Code Playgroud)
请注意,这是一个练习。(我尝试了大约1.5个小时,但没有找到任何解决方案。)
问:我在那里做错了什么?
当你陷入这样的困境时,我建议使用类型孔,因为它们会引导你走向正确的方向
\nfmap2 :: (Functor f, Functor g) => (a -> b) -> f (g a) -> f (g b)\nfmap2 f nested_functor = fmap _something nested_functor \n-- | | |- notice this underscore\n-- | |- clearly we need to fmap something over the nested_functor but we don\'t know what yet\n-- |- Using better names usually helps. Haskellers tend to use very short names, but that\'s not appropriate always\nRun Code Online (Sandbox Code Playgroud)\n如果您尝试编译此代码,ghc将会注意到_something并会建议您使用它的类型
Found hole: _something :: g a -> g b <-- This is interesting\n Where: \xe2\x80\x98a\xe2\x80\x99, \xe2\x80\x98g\xe2\x80\x99, \xe2\x80\x98b\xe2\x80\x99 ... (blah blah blah, not interesting)\n Or perhaps \xe2\x80\x98_something\xe2\x80\x99 is mis-spelled, or not in scope\nRun Code Online (Sandbox Code Playgroud)\n我们知道需要给出_something类型。因此:g a -> g bFunctor g
Found hole: _something :: g a -> g b <-- This is interesting\n Where: \xe2\x80\x98a\xe2\x80\x99, \xe2\x80\x98g\xe2\x80\x99, \xe2\x80\x98b\xe2\x80\x99 ... (blah blah blah, not interesting)\n Or perhaps \xe2\x80\x98_something\xe2\x80\x99 is mis-spelled, or not in scope\nRun Code Online (Sandbox Code Playgroud)\n