什么是 PHP 关联数组的 Haskell 等价性



在PHP中我可以这样做:

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

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

我的印象是您正在寻找一个键到值映射数据结构。在这种情况下,Haskell有containers包提供的Data.Map。它有几个变体,包括Data.Map。严格的,Data.Map。Lazy和Data.IntMap.

Haskell的默认map实现是有序的,并且基于平衡树,这使得操作的对数时间复杂度。但是在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

关于如何在Haskell中使用Map的更多上下文,摘自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")]

通常Data.Map是这类东西的最佳选择,但我想说的是,简单地使用元组的列表也是有意义的,这取决于您打算使用它。

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

这是更明智地称为数组,尽管在我看来,术语"关联"one_answers"数组"是相互矛盾的。无论如何,您可以在这样的列表上使用标准的lookup函数,只是要注意它具有O(n)复杂性,而不是专门设计的结构实现的O(1)或O(logn)。

相关内容

  • 没有找到相关文章

最新更新