Fetch the repository succeeded.
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
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。