Scala映射语法

Scala映射语法,scala,dictionary,Scala,Dictionary,在回顾Coursera Scala类中的倒水问题代码时,我遇到了map的两个用法,我不理解语法 我习惯于: a.map(b => b * b) 但我看到: a map something 例如: next <- moves map path.extend 这是否意味着“添加要探索的更多的结束状态” 在scala中,以下表达式是等效的: moves map path.extend moves map(path.extend) moves.map(path.extend) move

在回顾Coursera Scala类中的倒水问题代码时,我遇到了map的两个用法,我不理解语法

我习惯于:

a.map(b => b * b)
但我看到:

a map something
例如:

next <- moves map path.extend

这是否意味着“添加要探索的更多的结束状态”

在scala中,以下表达式是等效的:

moves map path.extend
moves map(path.extend)
moves.map(path.extend)
moves.map(m => path.extend(m))
more map (_.endstate)
more.map(_.endstate)
more.map(m => m.endstate)
以下是等效的:

moves map path.extend
moves map(path.extend)
moves.map(path.extend)
moves.map(m => path.extend(m))
more map (_.endstate)
more.map(_.endstate)
more.map(m => m.endstate)

回答你的第一个问题,我认为你关于
next b*b)的回答是正确的
//>res0:List[Int]=List(1,9,25)
为了{
废话b*b)
}产量胡说八道
//>res1:List[Int]=List(1,9,25)
您可以看到这两个函数返回相同的结果,并且在Scala中是等效的

所以我们说,对于“a”中的每个元素,调用函数(b=>b*b)


在您的示例中,更像是这样的场景:

case class Song(artists:List[String], title: String)

val songs = List(Song(List("Michael Jackson", "Janet Jackson"), "Scream"),
                             Song(List("Janet"), "Unbreakable"))

for {
  song <- songs
  artist <- song.artists
  if artist startsWith "Mic"
} yield song.title                                
  //> res0: List[String] =     List(Scream)

songs.flatMap(
    song => song.artists.withFilter(artist => artist startsWith "Mic").map(artist => song.title)
)                                                 
  //> res1: List[String] = List(Scream)
案例类歌曲(艺术家:列表[String],标题:String)
val songs=List(歌曲列表(“迈克尔·杰克逊”、“珍妮特·杰克逊”)、“尖叫”),
歌曲(名单(“珍妮特”),“牢不可破”))
为了{
song song.Artisters.withFilter(艺术家=>艺术家开始使用“麦克风”).map(艺术家=>song.title)
)                                                 
//>res1:List[String]=List(尖叫)

你可以看到它们也是等价的,但是“为了理解”更容易阅读。

Scala语法允许标准方法调用
obj.meth(arg)
用空格
obj-meth-arg
表示moves.map(path.extend)和
moves.map(m=>path.extend(m))
是不等价的:
def a(x:Int)(y:Int)=x+y;List(1).map(a);List(1).map(x=>a(x))
(最后一条语句不会编译)是的!我从这段代码中取了那一行:
def from(Path:Set[Path],explored:Set[State]):Stream[Set[Path]=if(Path.isEmpty)Stream.empty else{val more=for{在这种情况下,我认为它更像是平面图和带过滤器的组合。我在上面的答案中添加了一些新信息。希望能有所帮助。