我正在学习haskell,需要zipWith
使用定义函数foldr
。
我可以使用模式匹配和递归来做到这一点,但目前对我而言不起作用。例如:
zipWith' :: (a -> b -> c) -> [a] -> [b] -> [c]
zipWith' f = go
where
go [] _ = []
go _ [] = []
go (x:xs) (y:ys) = f x y : go xs ys
我也了解折叠的工作原理,但是我真的无法考虑如何使用折叠来定义zipWith
。
从已经非常感谢你。
您可以这样定义zipWith'
使用foldr
:
zipWith' :: (a -> b -> c) -> [a] -> [b] -> [c]
zipWith' f xs ys = fst $ foldr go ([], reverse xs) ys where
go _ (res, []) = (res, [])
go y (res, z:zs) = (f z y : res, zs)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句