5

我一直在玩 Pony 数组以更好地理解 Pony,并想为任何数组编写 map 函数。

我说的是当今大多数语言用于转换集合元素的标准 map 函数之类的东西,例如在 Clojure 中:

(map #(+ 1 %) [1 2 3]) ; => [2 3 4]

但我希望它实际修改给定的数组,而不是返回一个新数组。

到目前为止,由于功能,我目前的尝试遇到了许多错误:

// array is "iso" so I can give it to another actor and change it
let my_array: Array[U64] iso = [1; 2; 3; 4]

// other actor tries to recover arrays as "box" just to call pairs() on it
let a = recover box my_array end // ERROR: can't recover to this capability
for (i, item) in a.pairs() do
  // TODO set item at i to some other mapped value
  try my_array.update(i, fun(item))? end
end

任何人都知道如何做到这一点

4

1 回答 1

4

好吧,花了我一段时间,但我能够让事情正常进行。

这是我对正在发生的事情的基本理解(如果我错了,请纠正我)!

第一步是了解我们需要使用别名来更改 Pony 中变量的功能。

因此,为了使 iso 变量可用作盒子,必须通过基本上将其用作另一个变量的别名:

  let a: Array[U64] ref = consume array // array is "iso"
  for (i, item) in a.pairs() do
    try a.update(i, item + n)? end
  end

这行得通!

我遇到的另一个问题是我无法对生成的Array[U64] ref. 例如,不能将其传递给任何人。

所以我把整个东西包装成一个recover块,以便最终得到相同的数组,但作为一个val(对数组的不可变引用),它更有用,因为我可以将它发送给其他参与者:

let result = recover val
  let a: Array[U64] ref = consume array
  for (i, item) in a.pairs() do
    try a.update(i, item + n)? end
  end
  a
end

现在我可以发送result给任何人!

于 2019-02-24T09:59:53.647 回答