Content deleted Content added
Jesdisciple (talk | contribs) m →JavaScript: key types |
added haskell |
||
Line 236:
end;
</source>
=== Haskell ===
The [[Haskell (programming language)|Haskell]] programming language provides three different associative containers. The simplest is a list of pairs:
<pre>
m = [("Sally Smart", "555-9999"), ("John Doe", "555-1212"), ("J. Random Hacker", "553-1337")]
main = print (lookup "John Doe" m)
</pre>
output:
Just "555-1212"
Note that the lookup function returns a "Maybe" value, which is "Nothing" if not found, or "Just ''result''" when found.
The second is polymorphic functional maps (represented as immutable balanced binary trees):
<pre>
import qualified Data.Map as M
m = M.insert "Sally Smart" "555-9999" M.empty
m' = M.insert "John Doe" "555-1212" m
m'' = M.insert "J. Random Hacker" "553-1337" m'
main = print (M.lookup "John Doe" m'' :: Maybe String)
</pre>
output:
Just "555-1212"
A specialized version for integer keys also exists as Data.IntMap.
Finally, a polymorphic hash table:
<pre>
import qualified Data.HashTable as H
main = do m <- H.new (==) H.hashString
H.insert m "Sally Smart" "555-9999"
H.insert m "John Doe" "555-1212"
H.insert m "J. Random Hacker" "553-1337"
foo <- H.lookup m "John Doe"
print foo
</pre>
output:
Just "555-1212"
Lists of pairs and functional maps both provide a purely functional interface, which is more idiomatic in Haskell. In contrast, hash tables provide an imperative interface in the IO monad.
=== Java ===
|