首页 > 解决方案 > 在 Haskell 中更改数组中的条目

问题描述

假设你有

let a = array ((1,1),(2,2)) [((2,1),3),((1,2),2),((1,1),2),((2,2),3)]

现在我希望将最后一个元组中的 3 与某个数字相乘。我怎样才能做到这一点?

标签: arrayshaskell

解决方案


如果你想乘以5它会是:

accum (*) a [((2,2),5)]
--     ^  ^   ^     ^
--     function to combine values
--        array to read
--            one of the indices to manipulated
--                  value to give to f for the associated index

该函数的签名为

accum :: Ix i => (e -> a -> e) -> Array i e -> [(i, a)] -> Array i e

它的文档说:

accum f 接受一个数组和一个关联列表,并使用累加函数 f 将列表中的对累加到数组中。

因此,调用accum f arrayValue listWithPairsOfIndicesAndValues将调用在提供旧值和来自该索引的值时f给出的每个索引,并返回一个新数组,其中提到的所有位置都更新为相应调用返回的值。listWithPairsOfIndicesAndValueslistWithPairsOfIndicesAndValueslistWithPairsOfIndicesAndValuesf


推荐阅读