Scala中的反函数 [英] Inverse function in Scala

查看:186
本文介绍了Scala中的反函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以表达scala中任何函数的反函数?



例如,如果我有一个像这样的函数f


(x:Int)=> x + 1

(f(x):Int)=> x //不是一个有效的scala语法
$ b


/ b>




(x:Int) => inverse(f(x))// inverse将返回(x => x -1)

在斯卡拉做这种事情?



NB = x => x + 1就是这个例子,我正在寻找一种通用的方法来解决这类任务。

谢谢!

解决方案

不,像这样的东西是不可能的。问题是,并非所有的数学函数都有逆函数。从反向功能上的Wikipedia条目:


并非所有函数都有相反的。为了适用这个规则,每个元素y∈Y必须对应不超过一个x∈X;一个具有这个属性的函数被称为一对一,或信息保存或注入。

例如,平方根( sqrt )函数是平方函数( x ^ 2 )的倒数,仅当 x> = 0 ,其中平方根函数是一对一的。当 x <1时,可以说平方根函数的负值是平方函数的倒数。 0 仅因为 x ^ 2 =(-x)^ 2 。但是这是平方函数的一个特殊属性,通常情况下并不是这样。


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

Thanks!

解决方案

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.

这篇关于Scala中的反函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆