如何将字符串转换为运算符?

huangapple go评论138阅读模式
英文:

How can I turn a string into an operator?

问题

有没有一种方法可以将字符串(例如“+”,“-”,“/”,“”)转换为它们对应的数学运算符(+,-,/,)?

在Python中,你可以这样做:

import operator
ops = {"+": operator.add, "-": operator.sub} # 等等
print ops["+"](1,1) # 输出2

在Go语言中是否有类似的库或方法呢?

英文:

Is there a way to convert a string (e.g. "+", "-", "/", "*") into their respective math operators (+, -, /, *)?

In Python you can do:

import operator
ops = {"+": operator.add, "-": operator.sub} # etc.
print ops["+"](1,1) # prints 2

Is there a similar library or method for Go?

答案1

得分: 7

你可以使用函数值来实现这个:

ops := map[string]func(int, int) int{
    "+": func(a, b int) int { return a + b },
    "-": func(a, b int) int { return a - b },
    "*": func(a, b int) int { return a * b },
    "/": func(a, b int) int { return a / b },
}

fmt.Println(ops["+"](4, 2))
fmt.Println(ops["-"](4, 2))
fmt.Println(ops["*"](4, 2))
fmt.Println(ops["/"](4, 2))

输出结果为:

6
2
8
2

为了更好的打印结果:

a, b := 4, 2
for op, fv := range ops {
    fmt.Printf("%d %s %d = %d\n", a, op, b, fv(a, b))
}

输出结果为:

4 / 2 = 2
4 + 2 = 6
4 - 2 = 2
4 * 2 = 8

你可以在Go Playground上运行代码。

英文:

You can do this with function values:

ops := map[string]func(int, int) int{
	"+": func(a, b int) int { return a + b },
	"-": func(a, b int) int { return a - b },
	"*": func(a, b int) int { return a * b },
	"/": func(a, b int) int { return a / b },
}

fmt.Println(ops["+"](4, 2))
fmt.Println(ops["-"](4, 2))
fmt.Println(ops["*"](4, 2))
fmt.Println(ops["/"](4, 2))

Output: Go Playground

6
2
8
2

For a nice print:

a, b := 4, 2
for op, fv := range ops {
	fmt.Printf("%d %s %d = %d\n", a, op, b, fv(a, b))
}

Output:

4 / 2 = 2
4 + 2 = 6
4 - 2 = 2
4 * 2 = 8

答案2

得分: 4

有几种选择,但我建议使用switch语句或使用map[string]func来构建问题,并提供执行相同操作的函数。所以...可以选择以下两种方式之一:

ops := map[string]func(int, int) int{
    "+": func(a, b int) int { return a + b },
    "-": func(a, b int) int { return a - b },
    "*": func(a, b int) int { return a * b },
    "/": func(a, b int) int { return a / b },
}

或者

func doOp(op string, lhs, rhs int) int {
    switch op {
    case "+":
        return lhs + rhs
    // 其他操作符
    default:
        // 错误处理,因为给定了未知的操作符字符串
    }
}

我使用哪种方式可能取决于作用域。在我看来,函数更具可移植性。map不是只读的,所以例如其他人可以通过将不同的方法分配给"+"来完全破坏它。

编辑:经过思考,我认为map不好,不建议使用。函数更清晰、稳定、一致、可预测、封装等。

英文:

There are few options but I would recommend just constructing the problem in a switch or using a map[string]func to provide a function which does the same. So... Either this;

ops := map[string]func(int, int) int{
    "+": func(a, b int) int { return a + b },
    "-": func(a, b int) int { return a - b },
    "*": func(a, b int) int { return a * b },
    "/": func(a, b int) int { return a / b },
}

or this;

func doOp(string op, lhs, rhs int) int {
     switch (op) {
          case "+":
             return lhs + rhs
           // ect
           default:
              // error cause they gave an unknown op string
     }
}

Which I use would probably depend on scope. The function imo is more portable. The map isn't read only so for example someone else could just hose it entirely by assigning a different method to "+".

EDIT: After thinking about it the map sucks and I'd recommend against it. The function is more clear, stable, consistent, predictable, encapsulated ect.

答案3

得分: -1

这是另一种实现方式。这个实现比基于字符串的switch实现快大约3倍,但可读性稍差。

func RunOp(sign string, a, b int) int {
    s := byte(sign[0])
    switch s {
    case byte(43):
            return a+b
    case byte(45):
            return a-b
    case byte(47):
            return a/b
    case byte(42):
            return a*b
    default:
            return 0
    }
}
英文:

Here's another implementation. This is give or take 3x faster than the string-based switch implementation but readability is a little less.

func RunOp(sign string, a, b int) int {
    s := byte(sign[0])
    switch s {
    case byte(43):
            return a+b
    case byte(45):
            return a-b
    case byte(47):
            return a/b
    case byte(42):
            return a*b
    default:
            return 0
    }
}

huangapple
  • 本文由 发表于 2015年6月11日 03:10:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/30765238.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定