Inverse function in Scala

前端 未结 5 543
自闭症患者
自闭症患者 2021-01-02 23:01

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
         


        
5条回答
  •  迷失自我
    2021-01-02 23:17

    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.

提交回复
热议问题