Haskell中与PHP的关联数组相当的是什么?

3

在 PHP 中我可以这样做:

$array = [
    'A' => [1,2,3],
    'B' => [4,5,6],
    'C' => [7,8,9],
]

Haskell中等价于PHP关联数组的是什么?

2个回答

5
我的印象是你正在寻找一个键值对映射数据结构。在这种情况下,Haskell有Data.Map,由containers包提供。它有几个变体,包括Data.Map.StrictData.Map.LazyData.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

以下是来自 Data.Map 文档中关于在 Haskell 中使用 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")]

1
通常情况下,Data.Map 是处理这种情况的最佳选择,但我要指出,根据您想要做什么,使用一个元组列表也是有意义的。
array = [ ('A', [1,2,3])
        , ('B', [4,5,6])
        , ('C', [7,8,9]) ]

这是一种更合理地称为“数组”的东西,尽管我认为“关联”和“数组”这两个术语是互相矛盾的。无论如何,您可以在此类列表上使用标准的 lookup 函数,只需注意它具有 O (n) 的复杂度,而不是专门设计的结构所实现的 O (1) 或 O (log n)。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接