【问题标题】:zipWith Function Implemented Using Map and Zip Functions使用 Map 和 Zip 函数实现的 zipWith 函数
【发布时间】:2017-10-30 02:35:49
【问题描述】:

我正在尝试通过zipmap 函数实现zipWith 函数,但我收到一个错误消息:“错误:输入'::' 上的解析错误我的代码在下面并且我不确定我做错了什么

zipWith` :: (a -> b -> c) -> [a] -> [b] -> [c]
zipWith` f x y = zip x $ map f y

【问题讨论】:

  • 反引号 ` 不是变量名的有效字符。另外,为什么enter 在那里?这是一个错字还是你的源代码中实际上有enter这个词?它不属于。

标签: list haskell syntax syntax-error


【解决方案1】:

您必须使用 ' 符号而不是 ` ;然后,结合你需要使用的功能uncurry

zipWith' :: (a -> b -> c) -> [a] -> [b] -> [c]
zipWith' f xs ys  = map (uncurry f) (zip xs ys)

为什么,zip 的类型是:

zip :: [a] -> [b] -> [(a, b)]

但函数ff :: (a -> b -> c),所以,在uncurry的帮助下,

uncurry :: (a -> b -> c) -> (a, b) -> c

您可以将函数f 映射到[(a, b)],将其转换为[c]

【讨论】:

  • 为了最大程度的神秘:(<$> zip) <$> (<$>) <$> (<$>) <$> uncurry
  • 我不知道你为什么在几个小时前编辑了这个问题,但它使答案(包括你自己的!)无效,所以我回滚了。
  • @dfeuer 不错的一个,不可思议但也很有趣!感谢 cmets,回滚也是正确的
  • @dfeuer 需要解释一下吗?学习起来会很有趣。可能也很有启发性。
【解决方案2】:

正如 Damian 所指出的,zipWith` 不适用于尾随反引号——反引号在 Haskell 中具有特殊含义。将其重命名为zipWith'

zipWith' :: (a -> b -> c) -> [a] -> [b] -> [c]

那么你当然必须真正编写解决方案。有了显式递归,你就有了

zipWith' _ _ []          = []
zipWith' _ [] _          = []
zipWith' f (x:xs) (y:ys) = f x y : zipWith' f xs ys

但是使用mapzip 你可以这样应用它:

zipWith' f xs ys = map (\(x,y) -> f x y) . zip xs $ ys

或更容易阅读:

zipWith' f xs ys = map (\(x,y) -> f x y) zipped
    where zipped = zip xs ys

【讨论】:

    猜你喜欢
    • 2021-07-17
    • 2021-03-24
    • 2018-07-12
    • 1970-01-01
    • 1970-01-01
    • 2011-11-24
    • 2020-12-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多