Hacker News new | ask | show | jobs
by premium-concern 3433 days ago
> Also, Optionals are a light introduction to functors which is nice.

Optional is not a functor, in fact it violates the functor laws quite blatantly.

1 comments

I didn't assert they were functors. Just that seeing `map` on something that isn't a list should be somewhat eye-opening to someone who just casually uses it and isn't too familiar with functional programming, that was the point.

Also, when I wrote "functor" I was thinking of https://wiki.haskell.org/Functor, is that what you're thinking of? In that case, which of the rules does it break? if not, what definition of functor were you thinking of?

Optional.of(whatever).map(identityfunction) will definitely give you back an Optional<Whatever>... Am I missing something fundamental? Also Optional.of(whatever).map(f).map(y) is equivalent in return to Optional.of(whatever).map(f . y)... (of course that's not the java syntax for composing functions but I digress)

Consider two functions (excuse my Scala):

  val str: Function[String, String] = s => if (s.length > 3) s else null

  val num: Function[String, Integer] = s => if (s == null) -1 else s.length
With Optional, you receive different results depending on whether you call map twice, or combine the functions first:

  scala> Optional.of("Foo").map[String](str).map[Integer](num)
  res12: java.util.Optional[Integer] = Optional.empty

  scala> Optional.of("Foo").map[Integer](str.andThen(num))
  res15: java.util.Optional[Integer] = Optional[-1]
This is incorrect and violates the functor law.