【问题标题】:How to create a recursive zipWith function in Haskell?如何在 Haskell 中创建递归 zipWith 函数?
【发布时间】:2015-07-06 16:14:27
【问题描述】:

到目前为止我有:

miZipWith f [] [] = []
miZipWith f (x:xs) [] = []
miZipWith f [] (y:ys) = []
miZipWith f (x:xs) (y:ys) = f y: miZipWith f xs ys

----miZipWith f (x:xs) (y:ys) = f x : f y : miZipWith f xs ys

但这只会将函数 f 与第二个列表“压缩”。我如何也包含第一个列表?

*Main> miZipWith (*2) [1,2,3,4] [5,6,1]
[10,12,2]

【问题讨论】:

  • 你缺少的是f的类型是(a -> b -> c)

标签: list function haskell recursion


【解决方案1】:

zipWith 函数是这样的:

zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
zipWith f (x:xs) (y:ys) = f x y : zipWith f xs ys
zipWith _ _ _ = []

您的假设是函数f 只接受一个参数,但实际上它接受两个参数(两个列表的头部)。

【讨论】:

  • 技术上我知道,但它不会编译(即使在使用 zipWith 的定义定义 miZipWith 之后)。
  • :263:1: 无法从上下文 (Num (b -> c), Num b) 受 'it' 的推断类型约束: (Num (b -> c), Num b) => [c] at :263:1-32 'it' 具有推断类型'forall b c. (Num (b -> c), Num b) => [c]' 可能原因:推断类型不明确
  • miZipWith (*2) [1,2,3,4] [5,6,1] 现在应该是 miZipWith (*) [1,2,3,4] [5,6,1]
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-14
  • 2019-02-28
  • 2021-08-10
  • 2022-01-06
  • 2023-04-09
  • 1970-01-01
相关资源
最近更新 更多