forked from mndrix/golog
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclauses.go
83 lines (72 loc) · 1.73 KB
/
clauses.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package golog
import (
"strconv"
"github.com/mndrix/golog/term"
"github.com/mndrix/ps"
)
// clauses represents an ordered list of terms with
// cheap insertion at the front
// and back and deletion from anywhere.
// Each clause has a unique identifier
// which can be used for deletions
type clauses struct {
n int64 // number of terms in collection
lowestId int64
highestId int64
terms ps.Map // maps int64 => Term
}
// newClauses returns a new, empty list of clauses
func newClauses() *clauses {
var cs clauses
cs.terms = ps.NewMap()
// n, lowestId, highestId correctly default to 0
return &cs
}
// returns the number of terms stored in the list
func (self *clauses) count() int64 {
return self.n
}
// cons adds a term to the list's front
func (self *clauses) cons(t term.Term) *clauses {
cs := self.clone()
cs.n++
cs.lowestId--
key := strconv.FormatInt(cs.lowestId, 10)
cs.terms = self.terms.Set(key, t)
return cs
}
// cons adds a term to the list's back
func (self *clauses) snoc(t term.Term) *clauses {
cs := self.clone()
cs.n++
cs.highestId++
key := strconv.FormatInt(cs.highestId, 10)
cs.terms = self.terms.Set(key, t)
return cs
}
// all returns a slice of all terms, in order
func (self *clauses) all() []term.Term {
terms := make([]term.Term, 0)
if self.count() == 0 {
return terms
}
for i := self.lowestId; i <= self.highestId; i++ {
key := strconv.FormatInt(i, 10)
t, ok := self.terms.Lookup(key)
if ok {
terms = append(terms, t.(term.Term))
}
}
return terms
}
// invoke a callback on each clause
func (self *clauses) forEach(f func(term.Term)) {
for _, t := range self.all() {
f(t)
}
}
// returns a copy of this clause list
func (self *clauses) clone() *clauses {
cs := *self
return &cs
}