Is there a way to express the inverse of any function in Scala?
For example if I have a function f
like this:
(x: Int) => x + 1
Depending on your usage scenario you might be able to sort of do this by maintaining a map from (Function, Result) => Arguments
, and then call a method such as inverse(f, r)
which returns the arguments as stored in the map. However, this only works 1) if the original function is invoked before the inverse value is needed and 2) if the original function is injective (as ddk already pointed out).
There also is quite some implementation overhead involved (for example, you probably need a dedicated map for Function1
to Function22
), especially if you want to reduce the amount of boilerplate code imposed on function implementers. Aspect-oriented programming could help here, annotations similar to EJB3's Interceptors might also work.
It looks, though, as if the usage scenario must be a pretty special one to justify all the hoops you have to jump through.