list.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. package muesli
  2. // ListValue is a Muesli value with a list of other values.
  3. // Lists in Muesli are heterogenous, and can contain other Values of any type.
  4. type ListValue struct {
  5. RedispatchCallable
  6. List []Value
  7. }
  8. const ListType = TypeValue("List")
  9. func (v ListValue) Type() TypeValue { return ListType }
  10. func (val ListValue) String() string {
  11. res := "["
  12. sep := ""
  13. for _, elt := range val.List {
  14. if elt == nil {
  15. res = res + sep + "nil"
  16. } else {
  17. res = res + sep + elt.String()
  18. }
  19. sep = ", "
  20. }
  21. res += "]"
  22. return res
  23. }
  24. func (from * ListValue) Convert(to interface{}) error {
  25. switch toPtr := to.(type) {
  26. case *[]Value:
  27. (*toPtr) = from.List
  28. case **ListValue:
  29. (*toPtr) = from
  30. case *Value:
  31. (*toPtr) = from
  32. default:
  33. return NewErrorValuef("Cannot convert value %v to %v", from, to)
  34. }
  35. return nil
  36. }
  37. func NewListValue(elements ...Value) *ListValue {
  38. l := &ListValue{ List: elements }
  39. l.RedispatchCallable = NewRedispatchCallable("List", l)
  40. return l
  41. }
  42. func (list *ListValue) Append(elements ...Value) {
  43. list.List = append(list.List, elements...)
  44. }
  45. func (list *ListValue) AppendList(toAppend ListValue) {
  46. list.List = append(list.List, toAppend.List...)
  47. }
  48. func (list ListValue) Length() int {
  49. return len(list.List)
  50. }
  51. func (list *ListValue) Fetch(i int) Value {
  52. if i >= len(list.List) {
  53. return NilValue
  54. }
  55. return list.List[i]
  56. }
  57. func (list *ListValue) Place(i int, v Value) Value {
  58. if i >= len(list.List) {
  59. return NilValue
  60. }
  61. list.List[i] = v
  62. return list.List[i]
  63. }
  64. func (list *ListValue) First() Value {
  65. return list.Fetch(0)
  66. }
  67. func (list *ListValue) Last() Value {
  68. return list.Fetch(list.Length()-1)
  69. }
  70. func EmptyListValue() ListValue {
  71. lv := NewListValue()
  72. return *lv
  73. }
  74. func EmptyValueArray() []Value {
  75. return make([]Value, 0)
  76. }
  77. func NewValueArray(elements ...Value) []Value {
  78. return elements
  79. }