type checking and error handling for builtins improved.
Some checks failed
Build / build (push) Successful in 11m16s
Test / build (push) Failing after 17m0s

This commit is contained in:
Chuck Smith
2024-03-25 16:18:08 -04:00
parent 1c99d2198b
commit 6d234099d1
52 changed files with 650 additions and 433 deletions

View File

@@ -2,28 +2,30 @@ package builtins
import (
"monkey/object"
"monkey/typing"
"sort"
)
// Max ...
func Max(args ...object.Object) object.Object {
if len(args) != 1 {
return newError("wrong number of arguments. got=%d, want=1",
len(args))
if err := typing.Check(
"max", args,
typing.ExactArgs(1),
typing.WithTypes(object.ARRAY_OBJ),
); err != nil {
return newError(err.Error())
}
if a, ok := args[0].(*object.Array); ok {
// TODO: Make this more generic
xs := make([]int, len(a.Elements))
for n, e := range a.Elements {
if i, ok := e.(*object.Integer); ok {
xs = append(xs, int(i.Value))
} else {
return newError("item #%d not an `int` got=%s", n, e.Type())
}
a := args[0].(*object.Array)
// TODO: Make this more generic
xs := make([]int, len(a.Elements))
for n, e := range a.Elements {
if i, ok := e.(*object.Integer); ok {
xs = append(xs, int(i.Value))
} else {
return newError("item #%d not an `int` got=%s", n, e.Type())
}
sort.Ints(xs)
return &object.Integer{Value: int64(xs[len(xs)-1])}
}
return newError("argument #1 to `max` expected to be `array` got=%T", args[0].Type())
sort.Ints(xs)
return &object.Integer{Value: int64(xs[len(xs)-1])}
}