访问 Ziplist 中的位置
Accessing positions in a Ziplist
我刚刚发现 !!
运算符仅适用于列表:
(!!) :: [a] -> Int -> a
所以我在 hoogle:
搜索了替代品
我很惊讶没有找到一个!
所以我问:
- 在不将其转换回列表的情况下按索引访问 ziplist 的方法是什么?
- 什么 hoogle 搜索会找到它
当然,回答 1 对回答 2 有很大帮助,因为我有类型签名
ZipList
is a newtype
,所以有没有转换。就是同一个列表。
newtype ZipList a = ZipList { getZipList :: [a] }
正如报告在 section 4.2.3 Datatype Renamings 中所述,
A declaration of the form newtype cx => T u1 … uk = N t introduces a new type whose representation is the same as an existing type.
(强调我的)。当代码运行时,ZipList
标签根本不存在。因此,
getZipList
是一个 zero cost no-op.
例如,将 ZipList Int
值视为 [Int]
值是完全可以的。观察:
GHCi> coerce (ZipList [1,2,3] :: ZipList Int) :: [Int]
[1,2,3]
it :: [Int]
因此,数据构造函数 ZipList
只是一个编译时标记,我们通过它来声明要使用哪个应用程序实现的意图。具体来说,是压缩循环,而不是嵌套循环(常规 []
)。
至于!!
本身,应该避免。使用不断增长的索引值重复调用它会导致二次行为。可以使用任意数量的高阶函数,或者如果需要可以编写直接递归代码,一个一个地处理列表的元素,而无需为每个元素重新从头开始重新跟踪列表。
我刚刚发现 !!
运算符仅适用于列表:
(!!) :: [a] -> Int -> a
所以我在 hoogle:
搜索了替代品我很惊讶没有找到一个!
所以我问:
- 在不将其转换回列表的情况下按索引访问 ziplist 的方法是什么?
- 什么 hoogle 搜索会找到它
当然,回答 1 对回答 2 有很大帮助,因为我有类型签名
ZipList
is a newtype
,所以有没有转换。就是同一个列表。
newtype ZipList a = ZipList { getZipList :: [a] }
正如报告在 section 4.2.3 Datatype Renamings 中所述,
A declaration of the form newtype cx => T u1 … uk = N t introduces a new type whose representation is the same as an existing type.
(强调我的)。当代码运行时,ZipList
标签根本不存在。因此,
getZipList
是一个 zero cost no-op.
例如,将 ZipList Int
值视为 [Int]
值是完全可以的。观察:
GHCi> coerce (ZipList [1,2,3] :: ZipList Int) :: [Int]
[1,2,3]
it :: [Int]
因此,数据构造函数 ZipList
只是一个编译时标记,我们通过它来声明要使用哪个应用程序实现的意图。具体来说,是压缩循环,而不是嵌套循环(常规 []
)。
至于!!
本身,应该避免。使用不断增长的索引值重复调用它会导致二次行为。可以使用任意数量的高阶函数,或者如果需要可以编写直接递归代码,一个一个地处理列表的元素,而无需为每个元素重新从头开始重新跟踪列表。