haskell - PHP的关联数组的Haskell等价是什么
问题描述
在 PHP 中,我可以这样做:
$array = [
'A' => [1,2,3],
'B' => [4,5,6],
'C' => [7,8,9],
]
PHP 的关联数组的 Haskell 等价性是什么?
解决方案
我的印象是您正在寻找值映射数据结构的键。在那种情况下,Haskell 已经Data.Map
提供了containers
包。它有一些变体,包括 Data.Map.Strict、Data.Map.Lazy和Data.IntMap。
Haskell 的默认映射实现是有序的,并且基于平衡树,这使得操作具有对数时间复杂度。但是包中还有一个散列实现,unordered-containers
它提供了恒定的操作时间,但你当然不会得到默认的键顺序。
在您提供的 PHP 关联数组示例之后的一个简短示例:
import qualified Data.Map.Strict as Map
myMap = Map.fromList [ ('A',[1,2,3])
, ('B',[4,5,6])
, ('C',[7,8,9])
]
-- Looking up an existing key
Map.lookup 'B' myMap
> Just [4,5,6]
-- Looking up a non-existing key
Map.lookup 'Z' myMap
> Nothing
有关如何Map
在 Haskell 中使用 a 的更多上下文来自以下文档Data.Map
:
import qualified Data.Map.Strict as Map
nums = Map.fromList [(1,"one"), (2,"two"), (3,"three")]
-- Get the English word for the number 3 and 4.
Map.lookup 3 nums
> Just "three"
Map.lookup 4 nums
> Nothing
-- Add (4, "four") to our original map.
moreNums = Map.insert 4 "four" nums
Map.member 4 moreNums
> True
-- Remove the entry for 1 from our original map.
fewerNums = Map.delete 1 nums
Map.toAscList fewerNums
> [(2,"two"),(3,"three")]
-- Create a new map and combine it with our original map.
-- fromList is right-biased: if a key is repeated the rightmost value is taken.
newNums = Map.fromList [(3,"new three"), (4,"new four"), (4,"newer four")]
-- union is left-biased: if a key occurs more than once the value from the
-- left map is taken.
Map.union newNums nums
> fromList [(1,"one"),(2,"two"),(3,"new three"),(4,"newer four")]
推荐阅读
- http - 无法通过 Bearer 授权访问 HERE API
- python - 将 dataf 从 csv 移动到数据库时出现 sqlite3 错误,
- asp.net-core - 防伪停止带有 400 错误的基本剃须刀页面帖子
- angular - 如何从订阅的角度形式访问值?
- r - 如果输入已更改,则启用操作按钮
- angular - Angular ng-reflect-model 显示正确的值,但未反映在输入元素中
- html - 页面不滚动,文本不出现在标题下方,在正文中
- r - 有人可以帮我理解“函数(x)”中的代码,$out的作用是什么?
- bash - 在列中构建打印时连接具有相同模式的 2 行
- javascript - 检测 Edge Legacy 浏览器,而不是 Edge Chromium