我想写一个函数来修改列表中的某些元素,只要它们是一个特定的值。
例如,对于每一个等于10的数字,我想把列表中的下两个数字加到原来的数字上。[10、9、1、8、2、10、10、6、4、5、4、7、3、4、3、7、1]
那么我需要一个函数来返回:[20、9、1、8、2、26、20、6、4、5、4、7、3、4、3、7、1]
我已经探索过使用Map来实现这一点,但是我不知道如何使用列表中接下来的两个元素来获得Map,以便将它们添加到我想要修改的元素中。
到目前为止,这是我的代码。我知道它明显有缺陷,因为它重用了x:y:z的不变值
bowling :: [Int] -> [Int]
bowling (x:y:z:xs) = map (\x -> if (x == 10) then x + y + z else x) xs
b1 = bowling [10, 9, 1, 8, 2, 10, 10, 6, 4, 5, 4, 7, 3, 3, 4, 3, 7, 1]
我尝试使用Map来解决这个问题,但是我不知道如何创建一个函数来使用列表中的下两个元素。
1条答案
按热度按时间yr9zkbsy1#
仅仅用
map
确实是不可能的,但是可以用显式递归来实现,如下所示:如果你真的想用高阶函数来实现这一点,你可以用
mapAccumR
或para
来代替。例如,用mapAccumR
: