Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String + StringOps = functor?

My simple understanding of a functor is that it is just something that can be mapped over u.map(f) with the following constraints:-

  • f must be a function
  • f can return any value and the type is allowed to change
  • map must return a value of the same Functor ie. the shape and structure of the container must not change.

And an example.

scala> List(1, 2, 3).map(x => s"$x")
res8: List[String] = List(1, 2, 3)

My question:-

StringOps will implicitly wrap a java.lang.String to extend it with operations common to indexed sequences - such as map.

But the following confuses me a bit.

scala> "Tera".map(x => s"$x").map(x => s"$x")
res12: scala.collection.immutable.IndexedSeq[String] = Vector(T, e, r, a)

I assumed that map would return me just a scala.Predef.String rather than an IndexedSeq[String] since the definition of a functor is that it's shape/structure should remain the same.

Does this still meet the definition of a functor because scala.Predef.String IS-A IndexedSeq[String] ?

like image 367
jacks Avatar asked May 24 '26 15:05

jacks


1 Answers

No, String isn't a functor, precisely because it can only contain Chars.

Does this still meet the definition of a functor because scala.Predef.String IS-A IndexedSeq[String] ?

It isn't (it isn't IndexedSeq of anything, it's only implicitly convertible to IndexedSeq[Char]), and it doesn't.

like image 159
Alexey Romanov Avatar answered May 27 '26 15:05

Alexey Romanov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!