expr icon indicating copy to clipboard operation
expr copied to clipboard

Q: Get values of evaluated data/functions

Open simon-vasseur opened this issue 5 years ago • 5 comments

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.

simon-vasseur avatar Oct 07 '20 13:10 simon-vasseur

What do you mean by output? Just change expression. code := "filter(Tweets, {.Len <= 50})"

antonmedv avatar Oct 07 '20 17:10 antonmedv

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?"

simon-vasseur avatar Oct 07 '20 18:10 simon-vasseur

You can write you own helper for doing it. And use struct as env, save intermediate result in a field.

antonmedv avatar Oct 07 '20 18:10 antonmedv

Could you provide a snippet of this kind of helper ? Saving result of filter, then map, etc .. ? Thanks.

simon-vasseur avatar Oct 15 '20 07:10 simon-vasseur

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

antonmedv avatar Oct 15 '20 08:10 antonmedv