【问题标题】:Pass to map two elements of the list通过映射列表的两个元素
【发布时间】:2014-03-16 15:03:41
【问题描述】:

据我所知,map 函数采用函数 foo() 并列出并将函数 foo() 应用于列表的每个元素。换句话说 foo() 的参数是列表的当前元素:

*Main> map (+ 1) [0, 0, 0, 0]
[1,1,1,1]

但是,如果我想将 bar() 应用于 bar() 有两个参数的列表,该怎么办。在第一个简单示例中,列表的当前参数和下一个参数。类似的东西

bar current next
  | current > next = current * 2
  | otherwise = next -2

map bar [1, 2, 3, 2, 1]

在第二个更复杂的示例中,bar() 有两个参数:列表的当前元素和列表的 current+k 元素。比如:

bar shift current
  | current > next = current * 2
  | otherwise = next -2
  where next = <get current+shift element of the list>

map (bar 2) [1, 2, 3, 2, 1]

我该怎么做?

附言

我只是想在 Haskell 中重写这个 python 代码:

    for i in range (w, self.k + 1):
        if vector[i] > v + vector[i - w]:
            result[i] = vector[i]
        else:
            result[i] = v + vector[i - w]

【问题讨论】:

  • 在 Haskell 中使用空括号来表示函数并不常见(也没有用处)。最好这样说:“map 函数采用函数foo :: a-&gt;bas 列表并将foo 应用于每个元素”。当试图用文字表达事物时,类型系统有很大帮助,特别是对于那些不能简单地用过程术语表达和“函数应用于...”的东西。
  • 另外,在 Haskell 中 ()() 类型的值(实际上是 () 类型的唯一值,不包括底部)。 f()f () 相同,表示将函数f 应用于值(),因此以这种方式引用函数会混淆。

标签: haskell


【解决方案1】:

您可以使用zipWithdrop n

mapBar :: (Num a, Ord a) => Int -> [a] -> [a]
mapBar n list = zipWith bar list (drop n list)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-21
    • 1970-01-01
    • 2021-12-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多