-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmatch.go
39 lines (33 loc) · 808 Bytes
/
match.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
package main
import (
"context"
"regexp"
"github.com/hymkor/gmnlisp"
)
var rxCache = map[gmnlisp.String]*regexp.Regexp{}
func funMatch(ctx context.Context, w *gmnlisp.World, _pattern, _str gmnlisp.Node) (gmnlisp.Node, error) {
pattern, err := gmnlisp.ExpectClass[gmnlisp.String](ctx, w, _pattern)
if err != nil {
return nil, err
}
str, err := gmnlisp.ExpectClass[gmnlisp.String](ctx, w, _str)
if err != nil {
return nil, err
}
re, ok := rxCache[pattern]
if !ok {
re, err = regexp.Compile(string(pattern))
if err != nil {
return nil, err
}
}
matches := re.FindStringSubmatch(string(str))
var result gmnlisp.Node = gmnlisp.Null
for i := len(matches) - 1; i >= 0; i-- {
result = &gmnlisp.Cons{
Car: gmnlisp.String(matches[i]),
Cdr: result,
}
}
return result, nil
}