1 Star 0 Fork 0

blizzard/dsl

Create your Gitee Account
Explore and code with more than 14 million developers,Free private repositories !:)
Sign up
文件
Clone or Download
math.go 2.69 KB
Copy Edit Raw Blame History
blizzard authored 2026-01-06 14:19 +08:00 . feat: 实现内置函数库
package builtin
import (
"math"
"gitee.com/blizzard1413/dsl/function"
"gitee.com/blizzard1413/dsl/types"
)
// RegisterMath 注册所有数学函数
func RegisterMath(registry function.Registry) error {
mathFuncs := []struct {
name string
fn func([]interface{}) (interface{}, error)
sig *function.Signature
}{
{"Math.abs", mathAbs, function.NewSignature([]types.Type{types.NewNumberType()}, types.NewNumberType())},
{"Math.ceil", mathCeil, function.NewSignature([]types.Type{types.NewNumberType()}, types.NewNumberType())},
{"Math.floor", mathFloor, function.NewSignature([]types.Type{types.NewNumberType()}, types.NewNumberType())},
{"Math.round", mathRound, function.NewSignature([]types.Type{types.NewNumberType()}, types.NewNumberType())},
{"Math.sqrt", mathSqrt, function.NewSignature([]types.Type{types.NewNumberType()}, types.NewNumberType())},
{"Math.max", mathMax, function.NewVariadicSignature(1, types.NewNumberType())},
{"Math.min", mathMin, function.NewVariadicSignature(1, types.NewNumberType())},
{"Math.pow", mathPow, function.NewSignature([]types.Type{types.NewNumberType(), types.NewNumberType()}, types.NewNumberType())},
}
for _, mf := range mathFuncs {
if err := registry.RegisterNative(mf.name, mf.sig, mf.fn); err != nil {
return err
}
}
return nil
}
// mathAbs 返回数字的绝对值
func mathAbs(args []interface{}) (interface{}, error) {
x := toFloat64(args[0])
return math.Abs(x), nil
}
// mathCeil 向上取整
func mathCeil(args []interface{}) (interface{}, error) {
x := toFloat64(args[0])
return math.Ceil(x), nil
}
// mathFloor 向下取整
func mathFloor(args []interface{}) (interface{}, error) {
x := toFloat64(args[0])
return math.Floor(x), nil
}
// mathRound 四舍五入
func mathRound(args []interface{}) (interface{}, error) {
x := toFloat64(args[0])
return math.Round(x), nil
}
// mathSqrt 平方根
func mathSqrt(args []interface{}) (interface{}, error) {
x := toFloat64(args[0])
return math.Sqrt(x), nil
}
// mathMax 返回最大值
func mathMax(args []interface{}) (interface{}, error) {
if len(args) == 0 {
return math.Inf(-1), nil
}
max := toFloat64(args[0])
for i := 1; i < len(args); i++ {
val := toFloat64(args[i])
if val > max {
max = val
}
}
return max, nil
}
// mathMin 返回最小值
func mathMin(args []interface{}) (interface{}, error) {
if len(args) == 0 {
return math.Inf(1), nil
}
min := toFloat64(args[0])
for i := 1; i < len(args); i++ {
val := toFloat64(args[i])
if val < min {
min = val
}
}
return min, nil
}
// mathPow 幂运算
func mathPow(args []interface{}) (interface{}, error) {
base := toFloat64(args[0])
exponent := toFloat64(args[1])
return math.Pow(base, exponent), nil
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/blizzard1413/dsl.git
git@gitee.com:blizzard1413/dsl.git
blizzard1413
dsl
dsl
v1.2.0

Search