地图如何在Scala中的“选项"上工作? [英] How map work on Options in Scala?

查看:43
本文介绍了地图如何在Scala中的“选项"上工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这两个功能

  def pattern(s: String): Option[Pattern] =
try {
  Some(Pattern.compile(s))
} catch {
  case e: PatternSyntaxException => None
}

  def mkMatcher(pat: String): Option[String => Boolean] =
     pattern(pat) map (p => (s: String) => p.matcher(s).matches)

Map是将给定功能应用于列表的每个元素的高阶功能.

Map is the higher-order function that applies a given function to each element of a list.

现在我不明白上面声明中地图的工作方式.

Now I am not getting that how map is working here as per above statement.

推荐答案

Map是将给定功能应用于列表的每个元素的高阶函数.

Map is the higher-order function that applies a given function to each element of a list.

这是对map的限制性限制.

This is an uncommonly restrictive definition of map.

无论如何,它之所以有用,是因为它是由不坚持这一点的人定义的.

At any rate, it works because it was defined by someone who did not hold to that.

例如,某人写了类似的东西

For example, that someone wrote something akin to

sealed trait Option[+A] {
  def map[B](f: A => B): Option[B] = this match {
    case Some(value) => Some(f(value))
    case None => None
  }
}

作为标准库的一部分.这使得地图适用于 Option [A]

as part of the standard library. This makes map applicable to Option[A]

之所以定义它,是因为映射多种数据结构而不只是列表是有意义的.映射是一种应用于数据结构所包含元素的转换.

It was defined because it makes sense to map many kinds of data structures not just lists. Mapping is a transformation applied to the elements held by the data structure.

它将功能应用于每个元素.

It applies a function to each element.

Option [A] 可以被认为是一个琐碎的序列.它具有零个或一个元素.对其进行映射意味着将功能应用到其元素上(如果有的话).

Option[A] can be thought of as a trivial sequence. It either has zero or one elements. To map it means to apply the function on its element if it has one.

现在始终使用此功能可能没有多大意义,但是在某些情况下它很有用.

Now it may not make much sense to use this facility all of the time, but there are cases where it is useful.

例如,它是几种不同的方法之一,当存在时,启用启用 For Expressions 来对类型进行操作. Option [A] 可以用于方便的表达式.

For example, it is one of a few distinct methods that, when present enable enable For Expressions to operate on a type. Option[A] can be used in for expressions which can be convenient.

例如

val option: Option[Int] = Some(2)

val squared: Option[Int] = for {
  n <- option
  if n % 2 == 0
} yield n * n

有趣的是,这意味着 filter 也已在 Option [A] 上定义.

Interestingly, this implies that filter is also defined on Option[A].

如果您只有一个简单的值,那么使用一个不太通用的结构可能会更清楚.

If you just have a simple value it may well be clearer to use a less general construct.

这篇关于地图如何在Scala中的“选项"上工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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