Created
October 12, 2017 20:37
-
-
Save frenata/0298b2288f1dff4c6b8ac0b25b4685bc to your computer and use it in GitHub Desktop.
Haskell Hashtables!
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
table = mkHashTable 10 | |
table | |
|> insert ("bob", "bob metadata") | |
|> insert ("alice", "alice metadata") | |
|> delete "bob" | |
|> search "bob" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module HashTable | |
(mkHashTable, insert, search, delete) | |
where | |
import Data.Array (array, Array, (//), (!)) | |
import qualified Data.List as List | |
import Data.Hashable | |
data HashTable a b = | |
HashTable (Array Int [(a, b)]) | |
deriving Show | |
mkHashTable :: Eq a => Int -> HashTable a b | |
mkHashTable n = | |
HashTable (array(0,n-1) [(i,[]) | i <- [0..n-1]]) | |
insert :: Hashable a => (a, b) -> HashTable a b -> HashTable a b | |
insert (k, v) (HashTable arr) = | |
HashTable (arr // [(i, xs)]) | |
where | |
i = mHash (List.length arr) k | |
xs = (k,v) : (arr ! i) | |
search :: (Hashable a, Eq a) => a -> HashTable a b -> Maybe (a, b) | |
search key (HashTable arr) = | |
List.find (\(k,v) -> k == key) xs | |
where | |
i = mHash (List.length arr) key | |
xs = arr ! i | |
delete :: (Hashable a, Eq a, Eq b) => a -> HashTable a b -> HashTable a b | |
delete key (HashTable arr) = | |
case search key (HashTable arr) of | |
Nothing -> (HashTable arr) | |
Just (k,v) -> | |
HashTable (arr // [(i, newxs)]) | |
where | |
i = mHash (List.length arr) key | |
xs = arr ! i | |
newxs = List.delete (k,v) xs | |
mHash :: Hashable a => Int -> a -> Int | |
mHash n = | |
(`mod` n) . hash | |
len :: HashTable a b -> Int | |
len (HashTable arr) = List.length arr | |
(|>) = flip ($) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment