Scala 中的偏函数 [英] Partial Functions in Scala

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

问题描述

我只是想澄清一些有关 Scala 中部分定义函数的内容.我查看了文档,它说部分函数的类型是 PartialFunction[A,B],我可以定义一个部分函数,​​例如

I just wanted to clarify something about partially defined functions in Scala. I looked at the docs and it said the type of a partial function is PartialFunction[A,B], and I can define a partial function such as

val f: PartialFunction[Any, Int] = {...}

我想知道,对于 AB 类型,A 是一个参数,而 B 是一个返回类型?如果我有多个接受的类型,我是否使用 orElse 将部分函数链接在一起?

I was wondering, for the types A and B, is A a parameter, and B a return type? If I have multiple accepted types, do I use orElse to chain partial functions together?

推荐答案

在一个函数的集合论观点中,如果一个函数可以将定义域中的每一个值映射到范围内的一个值,我们就说这个函数是一个总功能.可能存在函数无法将域中的某些元素映射到范围的情况;此类函数称为部分函数.

In the set theoretic view of a function, if a function can map every value in the domain to a value in the range, we say that this function is a total function. There can be situations where a function cannot map some element(s) in the domain to the range; such functions are called partial functions.

以 Scala 文档中的部分函数为例:

Taking the example from the Scala docs for partial functions:

val isEven: PartialFunction[Int, String] = {
  case x if x % 2 == 0 => x+" is even"
}

这里定义了一个偏函数,因为它被定义为只将一个偶数整数映射到一个字符串.所以偏函数的输入是一个整数,输出是一个字符串.

Here a partial function is defined since it is defined to only map an even integer to a string. So the input to the partial function is an integer and the output is a string.

val isOdd: PartialFunction[Int, String] = {
  case x if x % 2 == 1 => x+" is odd"
}

isOdd 是另一个与 isEven 类似定义的偏函数,但用于奇数.同样,偏函数的输入是一个整数,输出是一个字符串.

isOdd is another partial function similarly defined as isEven but for odd numbers. Again, the input to the partial function is an integer and the output is a string.

如果您有一个数字列表,例如:

If you have a list of numbers such as:

List(1,2,3,4,5)

并在此列表上应用 isEven 部分函数,​​您将获得作为输出

and apply the isEven partial function on this list you will get as output

List(2 is even, 4 is even)

请注意,并非原始列表中的所有元素都已被偏函数映射.但是,在部分函数无法将元素从域映射到范围的情况下,可能存在您想要应用另一个函数的情况.在这种情况下,我们使用 orElse:

Notice that not all the elements in the original list have been mapped by the partial function. However, there may be situations where you want to apply another function in those cases where a partial function cannot map an element from the domain to the range. In this case we use orElse:

val numbers = sample map (isEven orElse isOdd)

现在你将得到输出:

List(1 is odd, 2 is even, 3 is odd, 4 is even, 5 is odd)

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

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