map.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package muesli
  2. // MapValue is a Muesli value with a hash map.
  3. // Maps in Muesli are heterogenous, and can contain other Values of any type.
  4. // Furtehmore any Value can be used as the hash map key.
  5. type MapValue struct {
  6. RedispatchCallable
  7. Map map[Value]Value
  8. }
  9. const MapType = TypeValue("Map")
  10. func (v MapValue) Type() TypeValue { return MapType }
  11. func (val MapValue) String() string {
  12. res := "{"
  13. sep := ""
  14. for k, v := range val.Map {
  15. res = res + sep + k.String() + "=>" + v.String()
  16. sep = ", "
  17. }
  18. res += "}"
  19. return res
  20. }
  21. func NewMapValue(elements map[Value]Value) * MapValue {
  22. mv := &MapValue{Map:elements}
  23. mv.RedispatchCallable = NewRedispatchCallable("List", mv)
  24. return mv
  25. }
  26. func (m *MapValue) Fetch(key Value) Value {
  27. var res Value
  28. var ok bool
  29. if res, ok = m.Map[key] ; !ok {
  30. return NilValue
  31. }
  32. return res
  33. }
  34. func (m *MapValue) Place(key Value, value Value) Value {
  35. m.Map[key] = value
  36. return m.Map[key]
  37. }
  38. func (from * MapValue) Convert(to interface{}) error {
  39. switch toPtr := to.(type) {
  40. case *map[Value]Value:
  41. (*toPtr) = from.Map
  42. case **MapValue:
  43. (*toPtr) = from
  44. case *Value:
  45. (*toPtr) = from
  46. default:
  47. return NewErrorValuef("Cannot convert value %v to %v", from, to)
  48. }
  49. return nil
  50. }