Math operator as argument

How do you create a function so that the math operator is an argument in form of symbol, eg. ‘+’, ‘-’, ‘**’? I saw a way to do this recently but I can’t remember where. I would like the operator to be a value in a dict and have a function perform the math on 2 numbers depending on the key.

I think you want perform: 3.perform('+', 4) – there are also variants performList performWithEnvir etc

1 Like

Rather than storing symbols that represent operators, it might be more general if you stored binary functions and used partial application.

a = (
	a: (_+_),
	b: (_*_),
	c: (_/_),
	d: (_ !? 1),
);

a.collect{ |f| f.(20, 3) }
('c': 6.6666666666667, 'a': 23, 'b': 60, 'd': 1)
2 Likes

Thank you both, just what I was looking for.

1 Like