elvish/pkg/eval/builtin_fn_pred.go

70 lines
1.2 KiB
Go
Raw Normal View History

package eval
import (
"src.elv.sh/pkg/eval/errs"
"src.elv.sh/pkg/eval/vals"
)
// Basic predicate commands.
func init() {
addBuiltinFns(map[string]any{
"bool": vals.Bool,
"not": not,
"is": is,
"eq": eq,
"not-eq": notEq,
"compare": compare,
})
}
func not(v any) bool {
return !vals.Bool(v)
}
func is(args ...any) bool {
for i := 0; i+1 < len(args); i++ {
if args[i] != args[i+1] {
return false
}
}
return true
}
func eq(args ...any) bool {
for i := 0; i+1 < len(args); i++ {
if !vals.Equal(args[i], args[i+1]) {
return false
}
}
return true
}
func notEq(args ...any) bool {
for i := 0; i+1 < len(args); i++ {
2018-02-15 17:14:05 +08:00
if vals.Equal(args[i], args[i+1]) {
return false
}
}
return true
}
// ErrUncomparable is raised by the compare and order commands when inputs contain
// uncomparable values.
var ErrUncomparable = errs.BadValue{
What: `inputs to "compare" or "order"`,
Valid: "comparable values", Actual: "uncomparable values"}
func compare(fm *Frame, a, b any) (int, error) {
2023-05-18 17:27:22 +08:00
switch vals.Cmp(a, b) {
case vals.CmpLess:
return -1, nil
2023-05-18 17:27:22 +08:00
case vals.CmpEqual:
return 0, nil
2023-05-18 17:27:22 +08:00
case vals.CmpMore:
return 1, nil
default:
return 0, ErrUncomparable
}
}