-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathprim_list_set.go
95 lines (82 loc) · 2.41 KB
/
prim_list_set.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
84
85
86
87
88
89
90
91
92
93
94
95
// Copyright 2015 SteelSeries ApS. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// This package implements a basic LISP interpretor for embedding in a go program for scripting.
// This file contains the list set-like primitive functions.
package golisp
import (
"fmt"
)
func RegisterListSetPrimitives() {
MakePrimitiveFunction("union", "*", UnionImpl)
MakePrimitiveFunction("intersection", "*", IntersectionImpl)
MakePrimitiveFunction("complement", "*", ComplementImpl)
}
func memp(i *Data, l *Data) bool {
for c := l; NotNilP(c); c = Cdr(c) {
if IsEqual(i, Car(c)) {
return true
}
}
return false
}
func UnionImpl(args *Data, env *SymbolTableFrame) (result *Data, err error) {
var col *Data
for a := args; NotNilP(a); a = Cdr(a) {
col = Car(a)
if !ListP(col) {
err = ProcessError(fmt.Sprintf("union needs lists as its arguments, but got %s.", String(col)), env)
return
}
for cell := col; NotNilP(cell); cell = Cdr(cell) {
if !memp(Car(cell), result) {
result = Append(result, Car(cell))
}
}
}
return
}
func IntersectionImpl(args *Data, env *SymbolTableFrame) (result *Data, err error) {
var col *Data
firstList := Car(args)
if !ListP(firstList) {
err = ProcessError(fmt.Sprintf("intersection needs lists as its arguments, but got %s.", String(firstList)), env)
return
}
result = Copy(firstList)
for a := Cdr(args); NotNilP(a); a = Cdr(a) {
col = Car(a)
if !ListP(col) {
err = ProcessError(fmt.Sprintf("intersection needs lists as its arguments, but got %s.", String(col)), env)
return
}
for cell := result; NotNilP(cell); cell = Cdr(cell) {
if !memp(Car(cell), col) {
result = RemoveFromListBang(result, Car(cell))
}
}
}
return
}
func ComplementImpl(args *Data, env *SymbolTableFrame) (result *Data, err error) {
var col *Data
firstList := Car(args)
if !ListP(firstList) {
err = ProcessError(fmt.Sprintf("complement needs lists as its arguments, but got %s.", String(firstList)), env)
return
}
result = Copy(firstList)
for a := Cdr(args); NotNilP(a); a = Cdr(a) {
col = Car(a)
if !ListP(col) {
err = ProcessError(fmt.Sprintf("complement needs lists as its arguments, but got %s.", String(col)), env)
return
}
for cell := result; NotNilP(cell); cell = Cdr(cell) {
if memp(Car(cell), col) {
result = RemoveFromListBang(result, Car(cell))
}
}
}
return
}