列表与映射(关键安全性与映射所有元素)
以下场景的最佳数据结构是什么?
假设您有一个 URL 列表
linkHaskell = Url "http://www.haskell.org"
linkReddit = Url "http://www.reddit.com"
...
,并且单独使用它们,但您还想对所有这些 URL 进行操作,例如链接检查,您可以将它们放在列表中
allLinks = [
linkHaskell
, linkReddit
...
]
但这很容易出错,因为您可能会忘记添加一个新链接。
您可以选择将这些 URL 存储在 Map 中,但随后您会将编译时错误替换为运行时错误,以防键中存在拼写错误。
在 Haskell 中你会做什么?
What is the best data structure for the following scenario?
Say, you have a list of URLs
linkHaskell = Url "http://www.haskell.org"
linkReddit = Url "http://www.reddit.com"
...
and you use them individually, but you also want to operate on all of them, e.g. link-check, you could put them in a list
allLinks = [
linkHaskell
, linkReddit
...
]
But that is error-prone, since you might forget to add a new link.
You could choose to store those URLs in a Map instead, but then you would exchange compile-time errors for runtime-errors, in case you have typos in the keys.
In Haskell what would you do?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一种简单的方法是为链接定义一种数据类型,即
您仍然必须在两个地方指定名称,但至少现在如果您忘记将其添加到一个地方(至少使用
-Wall ),编译器会抱怨)。
另一种方法是使用一些 Template Haskell 魔法:
现在您只需在一个位置指定链接:
One simple approach is to define a datatype for the links, i.e.
You still have to specify the name in two places, but at least now the compiler will complain if you forget to add it in one place (at least with
-Wall
).Another approach is to use some Template Haskell magic:
Now you only have to specify the links in one place: