scala - Map versus FlatMap on String -
listening collections lecture functional programming principles in scala, saw example:
scala> val s = "hello world" scala> s.flatmap(c => ("." + c)) // prepend each element period res5: string = .h.e.l.l.o. .w.o.r.l.d
then, curious why mr. odersky didn't use map
here. but, when tried map, got different result expected.
scala> s.map(c => ("." + c)) res8: scala.collection.immutable.indexedseq[string] = vector(.h, .e, .l, .l, .o, ". ", .w, .o, .r, .l,
i expected above call return string, since i'm map
-ing, i.e. applying function each item in "sequence," , returning new "sequence."
however, perform map
rather flatmap
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 indexedseq[string]
return type of calling map
on string?
the reason behavior that, in order apply "map" string, scala treats string sequence of chars (indexedseq[string]
). result of map invocation, each element of said sequence, operation applied. since scala treated string sequence apply map
, map
returns.
flatmap
invokes flatten
on sequence afterwards, "converts" string
Comments
Post a Comment