-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlist.go
59 lines (45 loc) · 1.18 KB
/
list.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package minimalisp
import "fmt"
// List is the interface for list implementations to fulfil.
type List interface {
First() interface{}
Rest() List
Add(el interface{}) List
Len() int
}
// ArrayList represents a simple array list implementation.
type ArrayList struct {
elements []interface{}
}
// First returns the first element of the ArrayList.
func (a *ArrayList) First() interface{} {
return a.elements[0]
}
// Rest returns all except the first element of the ArrayList
func (a *ArrayList) Rest() List {
return NewArrayList(a.elements[1:])
}
// Add returns all except the first element of the ArrayList
func (a *ArrayList) Add(el interface{}) List {
newElements := a.elements
newElements = append(newElements, el)
return NewArrayList(newElements)
}
// Len returns the length of the list.
func (a *ArrayList) Len() int {
return len(a.elements)
}
// NewArrayList is a factory function to create a new array list.
func NewArrayList(elements []interface{}) *ArrayList {
return &ArrayList{elements}
}
func (a *ArrayList) String() string {
var ret string = "("
for i, el := range a.elements {
if i != 0 {
ret += " "
}
ret += fmt.Sprintf("%v", el)
}
return ret + ")"
}