映射与FlatMap on String [英] Map versus FlatMap on String

查看:122
本文介绍了映射与FlatMap on String的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Scala中的功能规划原则收听收藏讲座,我看到了这个例子: / p>

  scala> val s =Hello World

scala> s.flatMap(c =>(。+ c))//前缀每个元素带有一个句点
res5:String = .H.e.l.l.o。 .World

然后,我很好奇为什么Odersky先生没有使用地图这里。但是,当我尝试地图时,我得到的结果不同于我的预期。

  scala> s.map(c =>(。+ c))
res8:scala.collection.immutable.IndexedSeq [String] = Vector(.H,.e,.l,.l,
。,.W,.o,.r,.l,

预期以上调用返回一个String,因为我是映射 -ing,即应用一个函数到序列中的每个项目,然后返回一个新的序列。



但是,我可以执行映射而不是 flatmap sList:List [Char] = List(H,e,l,l,o,,W,o,r,l,d)

scala> sList .map(c =>。+ c)
res9:List [String] = List(.H,.e,.l,.l,.o,。,.W, ,.r,.l,.d)

为什么是$ code IndexedSeq [ String] String上的调用 map 的返回类型

解决方案

这个行为的原因是为了将map应用于String,Scala将字符串视为一系列字符( IndexedSeq [String] )。这是由于地图调用所得到的,对于所述序列的每个元素,应用该操作。由于Scala将字符串作为序列应用 map ,这就是 map 返回。



flatMap 然后简单地调用该顺序的 flatten ,然后转换它返回一个字符串


Listening to the Collections lecture from Functional Programming Principles in Scala, I saw this example:

scala> val s = "Hello World"

scala> s.flatMap(c => ("." + c)) // prepend each element with a period
res5: String = .H.e.l.l.o. .W.o.r.l.d

Then, I was curious why Mr. Odersky didn't use a map here. But, when I tried map, I got a different result than I expected.

scala> s.map(c => ("." + c))
res8: scala.collection.immutable.IndexedSeq[String] = Vector(.H, .e, .l, .l, .o, 
                                                          ". ", .W, .o, .r, .l, 

I expected that above call to return a String, since I'm map-ing, i.e. applying a function to each item in the "sequence," and then returning a new "sequence."

However, I could perform a map rather than flatmap for a List[String]:

scala> val sList = s.toList
sList: List[Char] = List(H, e, l, l, o,  , W, o, r, l, d)

scala> sList.map(c => "." + c)
res9: List[String] = List(.H, .e, .l, .l, .o, ". ", .W, .o, .r, .l, .d)

Why was a IndexedSeq[String] the return type of calling map on the String?

解决方案

The reason for this behavior is that, in order to apply "map" to a String, Scala treats the string as a sequence of chars (IndexedSeq[String]). This is what you get as a result of the map invocation, where for each element of said sequence, the operation is applied. Since Scala treated the string as a sequence to apply map, that is what mapreturns.

flatMap then simply invokes flatten on that sequence afterwards, which then "converts" it back to a String

这篇关于映射与FlatMap on String的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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