-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
prolog.go
60 lines (54 loc) · 1.08 KB
/
prolog.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
package main
import (
"github.com/ichiban/prolog"
)
func (b *App) RunProlog(program string, input string) string {
//
// Create the output string.
//
b.err = ""
result := ""
//
// Create an interpreter instance.
//
p := prolog.New(nil, nil)
//
// Add the input as a clause for the program.
//
full := `intext("` + input + `").` + "\n" + program
//
// Load the program.
//
if err := p.Exec(full); err != nil {
//
// There was an error with the program.
//
b.err = err.Error()
} else {
//
// The program was loaded fine. Get the results.
//
sols, err := p.Query(`main(X).`)
if err != nil {
b.err = err.Error()
} else {
// Iterates over solutions.
for sols.Next() {
// Prepare a struct with fields which name corresponds with a variable in the query.
var s struct {
X string
}
if err := sols.Scan(&s); err != nil {
b.err = err.Error()
}
result += s.X + "\n"
}
}
defer sols.Close()
// Check if an error occurred while querying.
if err := sols.Err(); err != nil {
b.err = err.Error()
}
}
return result
}