Skip to content

Commit 967e0f8

Browse files
authored
vam: sqrt() (#5599)
1 parent a3e910c commit 967e0f8

File tree

4 files changed

+58
-2
lines changed

4 files changed

+58
-2
lines changed

runtime/sam/expr/function/math.go

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -170,9 +170,18 @@ type Sqrt struct {
170170
}
171171

172172
func (s *Sqrt) Call(_ super.Allocator, args []super.Value) super.Value {
173-
x, ok := coerce.ToFloat(args[0], super.TypeFloat64)
173+
val := args[0].Under()
174+
if id := val.Type().ID(); id == super.IDNull {
175+
return val
176+
} else if !super.IsNumber(id) {
177+
return s.zctx.WrapError("sqrt: number argument required", val)
178+
}
179+
if val.IsNull() {
180+
return super.NullFloat64
181+
}
182+
x, ok := coerce.ToFloat(val, super.TypeFloat64)
174183
if !ok {
175-
return s.zctx.WrapError("sqrt: not a number", args[0])
184+
return s.zctx.WrapError("sqrt: not a number", val)
176185
}
177186
return super.NewFloat64(math.Sqrt(x))
178187
}

runtime/vam/expr/function/function.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,8 @@ func New(zctx *super.Context, name string, narg int) (expr.Function, field.Path,
7070
case "split":
7171
argmin, argmax = 2, 2
7272
f = &Split{zctx}
73+
case "sqrt":
74+
f = &Sqrt{zctx}
7375
case "strftime":
7476
argmin, argmax = 2, 2
7577
f = &Strftime{zctx: zctx}

runtime/vam/expr/function/math.go

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -178,3 +178,27 @@ func (l *Log) Call(args ...vector.Any) vector.Any {
178178
}
179179
return out
180180
}
181+
182+
// https://github.com/brimdata/super/blob/main/docs/language/functions.md#sqrt
183+
type Sqrt struct {
184+
zctx *super.Context
185+
}
186+
187+
func (s *Sqrt) Call(args ...vector.Any) vector.Any {
188+
vec := vector.Under(args[0])
189+
if id := vec.Type().ID(); id == super.IDNull {
190+
return vec
191+
} else if !super.IsNumber(id) {
192+
return vector.NewWrappedError(s.zctx, "sqrt: number argument required", vec)
193+
}
194+
vec = cast.To(s.zctx, vec, super.TypeFloat64)
195+
vals := make([]float64, vec.Len())
196+
for i := range vec.Len() {
197+
v, isnull := vector.FloatValue(vec, i)
198+
if isnull {
199+
continue
200+
}
201+
vals[i] = math.Sqrt(v)
202+
}
203+
return vector.NewFloat(super.TypeFloat64, vals, vector.NullsOf(vec))
204+
}
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
zed: sqrt(this)
2+
3+
vector: true
4+
5+
input: |
6+
4
7+
2.
8+
1e10
9+
-1
10+
null(float64)
11+
null
12+
"9"
13+
14+
output: |
15+
2.
16+
1.4142135623730951
17+
100000.
18+
NaN
19+
null(float64)
20+
null
21+
error({message:"sqrt: number argument required",on:"9"})

0 commit comments

Comments
 (0)