-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlist.go
More file actions
104 lines (89 loc) · 1.69 KB
/
list.go
File metadata and controls
104 lines (89 loc) · 1.69 KB
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package main
import (
"strings"
)
type LispList struct {
first LispObject
rest *LispList
}
var LISP_NIL *LispList = new(LispList)
// Methods on LispList:
func (list *LispList) First() LispObject {
if list == LISP_NIL {
return LISP_NIL
}
return list.first
}
func (list *LispList) Second() LispObject {
return list.Rest().First()
}
func (list *LispList) Third() LispObject {
return list.Rest().Rest().First()
}
// Note: Nth(1) == First() & Nth(2) == Second()
func (list *LispList) Nth(n int) LispObject {
l := list
for {
if n <= 0 {
return LISP_NIL
} else if n == 1 {
return l.First()
}
l = l.Rest()
n--
}
return LISP_NIL
}
func (list *LispList) Rest() *LispList {
if list == LISP_NIL {
return LISP_NIL
}
return list.rest
}
func (list *LispList) String() string {
result := []string{}
if list == LISP_NIL {
return "nil"
}
result = append(result, "(")
for {
if list == LISP_NIL {
break
}
result = append(result, LispObject2String(list.First()))
list = list.Rest()
if list != LISP_NIL {
result = append(result, " ")
}
}
result = append(result, ")")
return strings.Join(result, "")
}
func Cons(first LispObject, rest *LispList) *LispList {
result := new(LispList)
result.first = first
result.rest = rest
return result
}
func ReverseList(list *LispList) *LispList {
ary := []LispObject{}
for {
if list == LISP_NIL {
break
}
ary = append(ary, list.First())
list = list.Rest()
}
result := LISP_NIL
for i := 0; i < len(ary); i++ {
result = Cons(ary[i], result)
}
return result
}
func List(args ...LispObject) *LispList {
result := LISP_NIL
for i := len(args) - 1; i >= 0; i-- {
result = Cons(args[i], result)
}
return result
}