有没有办法在 Scala 中表达任何函数的逆函数?
例如,如果我有一个函数 f
像这样:
(x: Int) => x + 1
我希望能够写一个反函数
g
喜欢:(f(x): Int) => x // not a valid scala syntax
或者
(x: Int) => inverse(f(x)) // inverse would return (x => x -1)
你知道在 Scala 中做这种事情的方法吗?
注:
x => x+1
只是为了举例。我正在寻找解决此类任务的通用方法。
最佳答案
不,这样的事情是不可能的。问题是并不是所有的数学函数都有逆。来自维基百科条目 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.
例如,平方根 (
sqrt
) 函数是平方函数 ( x^2
) 的逆函数,只有当 x >= 0
时,其中平方根函数是一对一的。当x < 0
时,我们可以说平方根函数的负数是平方函数的倒数。只因为x^2 = (-x)^2
.但这是平方函数的一个特殊属性,一般来说肯定不是这样。
关于function - Scala 中的反函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38166190/