Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inverse function in Scala

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

I would like to be able write an inverse function g like:

(f(x): Int) => x // not a valid scala syntax

or

(x: Int) => inverse(f(x)) // inverse would return (x => x -1)

Do you know a way to do this kind of thing in Scala?

N.B: x => x+1 is just for the example. I'm looking for a generic way to solve this kind of task.

like image 428
Loic Avatar asked Sep 27 '12 05:09

Loic


1 Answers

No, something like that is not possible. The problem is that not all mathematical functions have inverses. From the Wikipedia entry on inverse functions:

Not all functions have an inverse. For this rule to be applicable, each element y ∈ Y must correspond to no more than one x ∈ X; a function ƒ with this property is called one-to-one, or information-preserving, or an injection.

For example, the square root (sqrt) function is the inverse of the square function (x^2) only when x >= 0, where the square root function is one-to-one. We can say that the negative of the square root function is the inverse of the square function when x < 0 only because x^2 = (-x)^2. But that is a special property of the square function and is certainly not true in general.

like image 190
ddk Avatar answered Oct 07 '22 19:10

ddk