Implement builtin len.

This commit is contained in:
Qi Xiao 2016-02-15 23:00:21 +01:00
parent 5000c60813
commit b8e831f709

View File

@ -67,6 +67,7 @@ func init() {
&BuiltinFn{"take", wrapFn(take)},
&BuiltinFn{"drop", wrapFn(drop)},
&BuiltinFn{"len", wrapFn(lenFn)},
&BuiltinFn{"count", wrapFn(count)},
&BuiltinFn{"-sleep", wrapFn(_sleep)},
@ -508,6 +509,23 @@ func drop(ec *EvalCtx, n int) {
}
}
func lenFn(ec *EvalCtx, v Value) {
var l int
switch v := v.(type) {
case String:
l = len(v)
case List:
l = len(*v.inner)
case Map:
l = len(*v.inner)
case *Struct:
l = len(v.FieldNames)
default:
throw(fmt.Errorf("cannot get length of a %s", v.Kind()))
}
ec.ports[1].Chan <- String(strconv.Itoa(l))
}
func count(ec *EvalCtx) {
in := ec.ports[0].Chan
out := ec.ports[1].Chan