do not use funky.Maybe for results - stick to Go idiom with ok or error

This commit is contained in:
Helmut Merz 2023-07-31 14:47:04 +02:00
parent 84d81a681a
commit 373c9484c8
4 changed files with 24 additions and 27 deletions

View file

@ -4,10 +4,6 @@
// slice is the current value.
package voc
import (
"git.sr.ht/~cco/go-scopes/common/funky"
)
type VocData[V any] map[string][]V
type Vocabulary[V any] struct {
@ -30,13 +26,14 @@ func (voc *Vocabulary[V]) Register(name string, it V) {
}
}
func (voc *Vocabulary[V]) Lookup(name string) funky.Maybe[V] {
func (voc *Vocabulary[V]) Lookup(name string) (V, bool) {
vi, ok := voc.data[name]
if ok {
return funky.Just(vi[len(vi)-1])
return vi[len(vi)-1], true
}
if voc.parent != nil {
return voc.parent.Lookup(name)
}
return funky.Nothing[V]()
var r V
return r, false
}

View file

@ -10,13 +10,12 @@ type builtins struct {
}
func Get(f FE) *builtins {
m := f.Voc().Lookup("builtins")
if m.IsNothing() {
b := setup(f)
f.Voc().Register("builtins", b)
return b
if v, ok := f.Voc().Lookup("builtins"); ok {
return v.(*builtins)
}
return m.Value().(*builtins)
b := setup(f)
f.Voc().Register("builtins", b)
return b
}
func setup(f FE) *builtins {

View file

@ -1,7 +1,8 @@
package rep
import (
"git.sr.ht/~cco/go-scopes/common/funky"
"fmt"
"git.sr.ht/~cco/go-scopes/forge"
)
@ -23,21 +24,21 @@ func (ci code) Compile(f forge.FE) forge.FPtr {
case int:
c.Append(i)
case string:
m := compStr(f, i)
if !m.IsNothing() {
c.Append(m.Value())
if v, err := compStr(f, i); err == nil {
c.Append(v)
} else {
fmt.Println(err)
}
}
}
return c.Reset()
}
func compStr(f forge.FE, s string) funky.Maybe[forge.FItem] {
mxt := f.Voc().Lookup(s)
if mxt.IsNothing() {
return funky.Nothing[forge.FItem]()
func compStr(f forge.FE, s string) (forge.FItem, error) {
if v, ok := f.Voc().Lookup(s); ok {
return forge.FItem(v), nil
}
return funky.Just(forge.FItem(mxt.Value()))
return nil, fmt.Errorf("not found: %s", s)
}
// defs - definitions, represented by a map

View file

@ -40,11 +40,11 @@ func StackTest(t *testing.T) {
func VocTest(t *testing.T) {
v1 := voc.NewVoc[int](nil)
v1.Register("one", 1)
m := v1.Lookup("one")
t.AssertEqual(m.IsNothing(), false)
t.AssertEqual(m.Value(), 1)
m = v1.Lookup("two")
t.AssertEqual(m.IsNothing(), true)
r1, ok := v1.Lookup("one")
t.AssertEqual(ok, true)
t.AssertEqual(r1, 1)
_, ok = v1.Lookup("two")
t.AssertEqual(ok, false)
}
func PtrValuePointerTest(t *testing.T) {