Guest User

Untitled

a guest
Oct 16th, 2017
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.39 KB | None | 0 0
  1. {-# LANGUAGE GADTs #-}
  2.  
  3. module Lib where
  4.  
  5. import qualified Data.HashMap.Lazy as M
  6. import Data.Hashable
  7. import Data.Typeable
  8.  
  9. -- this is what we know about all things from Java
  10. data Val where
  11. Val :: (Eq a, Hashable a, Typeable a) => a -> Val
  12.  
  13. instance Hashable Val where
  14. hashWithSalt salt (Val a) = hashWithSalt salt a
  15.  
  16. instance Eq Val where
  17. Val a == Val b =
  18. case cast b of
  19. Nothing -> False
  20. Just bb -> a == bb
  21.  
  22. examine :: (Typeable a, Hashable a) => Val -> Maybe a
  23. examine (Val a) = cast a
  24.  
  25. -- simplified, slightly, we won't do variadic inputs
  26. assoc :: Val -> Val -> Val -> Val
  27. assoc map key val =
  28. case examine map of
  29. Nothing -> error "not bothering with failure semantics"
  30. Just mapS -> Val (M.insert key val mapS)
  31.  
  32. get :: Val -> Val -> Val
  33. get map key =
  34. case examine map of
  35. Nothing -> error "not bothering with failure semantics"
  36. Just mapS -> mapS M.! key
  37.  
  38. {-
  39.  
  40. (defn assoc-in
  41. "Associates a value in a nested associative structure, where ks is a
  42. sequence of keys and v is the new value and returns a new nested structure.
  43. If any levels do not exist, hash-maps will be created."
  44. {:added "1.0"
  45. :static true}
  46. [m [k & ks] v]
  47. (if ks
  48. (assoc m k (assoc-in (get m k) ks v))
  49. (assoc m k v)))
  50.  
  51. -}
  52. assocIn :: Val -> [Val] -> Val -> Val
  53. assocIn _ [] _ = error "more unhandled errors"
  54. assocIn m [k] v = assoc m k v
  55. assocIn m (k:ks) v = assoc m k (assocIn (get m k) ks v)
Add Comment
Please, Sign In to add comment