繁体   English   中英

传递以映射列表的两个元素

[英]Pass to map two elements of the list

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

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

但是,如果我想将bar()应用于其中bar()有两个参数的列表,该怎么办? 在第一个简单示例中,列表的are当前和next参数。 就像是

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]

我怎样才能做到这一点 ?

ps

我只想在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]

您可以使用zipWithdrop n

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM