Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Go support operator type variables?

This is might not be such a good question, since I don't know of any compiled language that supports this feature, but since Go is constantly surprising me, I'll ask it anyway:

For my own practice, I am writing a little calculator program in Go. I'm wondering if there is a way I can declare and assign a variable of type "Operator", such that I could, for example, write:

var o Operator

o = +

var o1 Operator

o1 = /

and write function like this

func DoOperation(a,b int,o Operator) int{

    return a o b

}

(No, I am not asking about operator overloading.)

Offhand, I don't know of any compiled language that supports such a thing (I'm not an expert in this). I did look at the docs under operators and found nothing. Can Go surprise me again?

Edit: The accepted answer states that Haskell supports this,

like image 852
Vector Avatar asked Mar 25 '14 06:03

Vector


1 Answers

No, Go operators are not functions and hence no valid right-hand expressions. They work in a generic way e.g. the plus-operator works on all numeric types and infix-notation a la haskell is not supported either.

You would have to write your own "soft"-generic addition function using reflection.

One compiled language that covers all of your requirements is Haskell.

like image 75
thwd Avatar answered Oct 12 '22 00:10

thwd