Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

vam: round() #5598

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions runtime/sam/expr/function/math.go
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,9 @@ func (r *Round) Call(_ super.Allocator, args []super.Value) super.Value {
case super.IsUnsigned(id) || super.IsSigned(id):
return val
case super.IsFloat(id):
if val.IsNull() {
return val
}
return super.NewFloat(val.Type(), math.Round(val.Float()))
}
return r.zctx.WrapError("round: not a number", val)
Expand Down
2 changes: 2 additions & 0 deletions runtime/vam/expr/function/function.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,8 @@ func New(zctx *super.Context, name string, narg int) (expr.Function, field.Path,
case "replace":
argmin, argmax = 3, 3
f = &Replace{zctx}
case "round":
f = &Round{zctx}
case "rune_len":
f = &RuneLen{zctx}
case "split":
Expand Down
21 changes: 21 additions & 0 deletions runtime/vam/expr/function/math.go
Original file line number Diff line number Diff line change
Expand Up @@ -178,3 +178,24 @@ func (l *Log) Call(args ...vector.Any) vector.Any {
}
return out
}

// https://github.com/brimdata/super/blob/main/docs/language/functions.md#round
type Round struct {
zctx *super.Context
}

func (r *Round) Call(args ...vector.Any) vector.Any {
vec := args[0]
switch id := vec.Type().ID(); {
case super.IsUnsigned(id) || super.IsSigned(id):
return vec
case super.IsFloat(id):
vals := make([]float64, vec.Len())
for i := range vec.Len() {
v, _ := vector.FloatValue(vec, i)
vals[i] = math.Round(v)
}
return vector.NewFloat(vec.Type(), vals, vector.NullsOf(vec))
}
return vector.NewWrappedError(r.zctx, "round: not a number", vec)
}
19 changes: 19 additions & 0 deletions runtime/ztests/expr/function/round.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
zed: "round(this)"

vector: true

input: |
-1
2(uint64)
1.5
2.4
null(float64)
"foo"
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe add null?


output: |
-1
2(uint64)
2.
2.
null(float64)
error({message:"round: not a number",on:"foo"})