使用 STArray 并忽略 Purescript 中修改的 return

Using STArray and ignore the return of modify in Purescript

我想我已经接近我想要的了,尽管我怀疑我不明白 thaw / TH Region 是如何工作的。

这是我要实现的(至少是粗略的)

modifyPerIndex :: forall t a. Foldable t => t (Tuple Int (a -> a)) -> Array a -> Array a
modifyPerIndex foldableActions array = run do
  mutableArray <- thaw array
  let actions = fromFoldable foldableActions
  foreach actions (\(Tuple index action) -> modify index action mutableArray)
  freeze mutableArray

这就是我想象中 updateAtIndices 的工作方式。我想我可以通过读取值、应用 (a -> a) 并将结果映射到要发送到 updateAtIndices 的元组列表来编写 modifyPerIndex 来使用 updateAtIndices

不过我很好奇怎么做。

上面的代码modify returns ST h Boolean,我想改成ST h Unit。那就是我迷路的地方。我知道 h 这是对可变数据的约束,以阻止它离开 run,我不明白的是如何使用它。

有几个选项。但是和h没有关系。您不必为任何事情“使用”它,也完全不必担心它。

首先,最愚蠢和直接的方法 - 只需将结果绑定到一个被忽略的变量,然后单独 return unit:

foreach actions \(Tuple index action) -> do
  _ <- modify index action mutableArray
  pure unit

或者,您可以使用 void,它在幕后做的事情大致相同:

foreach actions \(Tuple index action) -> void $ modify index action mutableArray

但我会直接选择 for_,这与 foreach 相同,但适用于任何 monad(不仅仅是 ST)并忽略单个迭代'return 值:

for_ actions \(Tuple index action) -> modify index action mutableArray