Home > other >  What is the Haskell equivalence of PHP's associative array
What is the Haskell equivalence of PHP's associative array

Time:10-25

In PHP I can do this:

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

What is the Haskell equivalence of PHP's associative array?

CodePudding user response:

My impression is that you are looking for a key to value map data structure. In that case Haskell has Data.Map provided by the containers package. There are a few variations to it including Data.Map.Strict, Data.Map.Lazy, and Data.IntMap.

Haskell's default map implementations are ordered and based on a balanced tree which makes operations of logarithmic time complexity. But there is also a hashing implementation in the unordered-containers package which provides for constant operation times but you don't get the default ordering of keys of course.

A short example following the PHP associative array example that you provided:

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

Some more context on how to use a Map in Haskell taken from the documentation of 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")]

CodePudding user response:

Usually Data.Map is the best for this kind of stuff, but I'd remark that it can also make sense to simply use a list of tuples, depending want you intend to do with this.

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

This is something that's more sensibly called array, though IMO the terms “associative” and “array” are mutually contradicting. At any rate you can use the standard lookup function on such lists, just be aware that it has O (n) complexity instead of the O (1) or O (log n) that purpose-designed structures achieve.

  • Related