gpt4 book ai didi

haskell - 在什么意义上 (# a #) 是单元素未装箱元组,与 'a' 不同?

转载 作者:行者123 更新时间:2023-12-02 01:51:02 25 4
gpt4 key购买 nike

Data.Primitive.SmallArray ,功能如下:

indexSmallArray## :: SmallArray a -> Int -> (#a#)
它以一个元素返回其结果 unboxed tuple .
我的问题是:我们从返回未装箱的元组中得到什么?为什么不简单地返回 a ?
我确实得到了多个元素的未装箱元组的用处。作为 Levity Polymorphism纸说:

Originally conceived to support returning multiple values from afunction, an unboxed tuple is merely Haskell syntax for tying multiplevalues together. Unboxed tuples do not exist at runtime, at all[...] during compilation, the unboxed tuple is erased completely

最佳答案

似乎目的是将索引到数组的工作与“强制”a 分离。本身到 WHNF。
如果我们简单地返回 a ,然后评估对 indexSmallArray## 的调用to WHNF 将执行索引并将结果评估为 WHNF。(# a #) 上的模式匹配将执行索引(从而释放对隐藏在 thunk 后面的数组的引用,可能允许对数组进行垃圾收集)但不强制单个组件 a到 WHNF(据我们所知,它可能是 undefined)。
docs对于使用类似技术的primop,我们发现:

primop IndexArrayOp "indexArray#" GenPrimOp
Array# a -> Int# -> (#> a #)
{Read from specified index of immutable array. Result ispackaged intoan unboxed unary tuple; the result itself is not yet evaluated. Patternmatching on the tuple forces the indexing of the arrayto happen but does not evaluate the element itself. Doing thispattern match immidiately can be useful for (1) preventingadditional thunks from building up on the heap and (2) eliminatingreferences to the argument array, allowing it to be garbagecollected more promptly.}


我想我们可以使用像 data Wrap a = Wrap a 这样的包装器类型来完成同样的任务。 ,但这会导致不必要的堆分配,而未装箱的元组不会发生这种情况。

关于haskell - 在什么意义上 (# a #) 是单元素未装箱元组,与 'a' 不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63441862/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com