Exemple #1
0
//!+parseAndCheck
func parseAndCheck(s string) (eval.Expr, error) {
	if s == "" {
		return nil, fmt.Errorf("empty expression")
	}
	expr, err := eval.Parse(s)
	if err != nil {
		return nil, err
	}
	vars := make(map[eval.Var]bool)
	if err := expr.Check(vars); err != nil {
		return nil, err
	}
	for v := range vars {
		if v != "x" && v != "y" && v != "r" {
			return nil, fmt.Errorf("undefined variable: %s", v)
		}
	}
	return expr, nil
}
Exemple #2
0
func main() {
	handler := func(w http.ResponseWriter, r *http.Request) {
		q := r.URL.Query()
		d := &data{"", 0.0}

		if len(q["expr"]) > 0 {
			d.Expr = q["expr"][0]
			expr, err := eval.Parse(q["expr"][0])
			if err == nil {
				d.Result = expr.Eval(eval.Env{})
			}
		}
		calc.Execute(w, d)
	}

	http.HandleFunc("/", handler)
	log.Println("Running server in localhost:8000 ...")
	log.Fatal(http.ListenAndServe("localhost:8000", nil))
}
Exemple #3
0
func main() {
	exitCode := 0
	stdin := bufio.NewScanner(os.Stdin)
	fmt.Printf("Expression: ")
	stdin.Scan()
	expr, err := eval.Parse(stdin.Text())
	if err != nil {
		fmt.Fprintf(os.Stderr, "bad expression: %s\n", err)
		os.Exit(1)
	}

	fmt.Printf("Variables (<var>=<val>, eg: x=3 y=5 ...): ")
	stdin.Scan()
	envStr := stdin.Text()
	if stdin.Err() != nil {
		fmt.Fprintln(os.Stderr, stdin.Err())
		os.Exit(1)
	}

	env := eval.Env{}
	assignments := strings.Fields(envStr)
	for _, a := range assignments {
		fields := strings.Split(a, "=")
		if len(fields) != 2 {
			fmt.Fprintf(os.Stderr, "bad assignment: %s\n", a)
			exitCode = assignment_error
		}
		ident, valStr := fields[0], fields[1]
		val, err := strconv.ParseFloat(valStr, 64)
		if err != nil {
			fmt.Fprintf(os.Stderr, "bad value for %s, using zero: %s\n", ident, err)
			exitCode = assignment_error
		}
		env[eval.Var(ident)] = val
	}

	fmt.Println(expr.Eval(env))
	os.Exit(exitCode)
}
Exemple #4
0
func main() {
	expr, _ := eval.Parse("pow(x + pow(y))")
	fmt.Println(expr.String())
}
Exemple #5
0
func main() {
	expr, _ := eval.Parse("pow(x,min(1.5,2))")
	fmt.Println(expr.Eval(eval.Env{"x": 4}))
}