Q: Get values of evaluated data/functions
Hi,
Thanks for an awesome library !
Quick question regarding this code, for example.
type Tweet struct {
Len int
}
type Env struct {
Tweets []Tweet
}
func main() {
code := "len(filter(Tweets, {.Len <= 50})) >= 1"
program, err := expr.Compile(code, expr.Env(Env{}))
if err != nil {
panic(err)
}
env := Env{
Tweets: []Tweet{{42}, {98}, {69}},
}
output, err := expr.Run(program, env)
if err != nil {
panic(err)
}
fmt.Println(output)
}
Is it possible to access the output of filter(Tweets, {.Len <= 50}) and/or len(filter(Tweets, {.Len <= 50})) ? Maybe with Patch ?
https://github.com/antonmedv/expr/blob/master/docs/Visitor-and-Patch.md
Regards.
What do you mean by output? Just change expression. code := "filter(Tweets, {.Len <= 50})"
Sorry, my question was confusing.
I mean, knowing the content of the filter and the value of len, but the expression output is still a boolean.
Answering the question: "ok the expression match, cool, it's > 1. But how many tweets in fact?"
You can write you own helper for doing it. And use struct as env, save intermediate result in a field.
Could you provide a snippet of this kind of helper ? Saving result of filter, then map, etc .. ? Thanks.
package main
import (
"fmt"
"github.com/antonmedv/expr"
)
type Tweet struct {
Len int
}
type Env struct {
Tweets []Tweet
savedLen int
}
func (e *Env) Len(arr []Tweet) int {
e.savedLen = len(arr)
return e.savedLen
}
func main() {
code := "Len(Tweets) >= 1"
program, err := expr.Compile(code, expr.Env(&Env{}))
if err != nil {
panic(err)
}
env := &Env{
Tweets: []Tweet{{42}, {98}, {69}},
}
output, err := expr.Run(program, env)
if err != nil {
panic(err)
}
fmt.Println(output)
fmt.Println(env.savedLen)
}
https://play.golang.org/p/bD26p6SjvYU