title: Functional composition of Optionals
body: <p>I have 2 Optionals (or Maybe objects) that I would like to combine so that I get the following results:</p>
  <pre><code>                ||       first operand 
      second      ++-------------+-------------
      operand     ||    empty    | optional(x)
      ============||=============|=============
      empty       ||    empty    | optional(x)
      ------------++-------------+-------------
      optional(y) || optional(y) |optional(x+y)
  </code></pre>
  <p>In other words, a non-empty Optional always replaces/overwrites an empty one, and two non-empty Optionals are combined according to some <code>+</code> function.</p>
  <p>Initially, I assumed that the standard monadic <code>flatMap</code> method would do the trick, but (at least in Java) <code>Optional.flatMap</code> always returns an empty optional when the original Optional was already empty (and I'm not sure if any other implementation would comply with the Monad Laws).</p>
  <p>Then, as both operands are wrapped in the same monadic type, I figured that this might be a good job for an Applicative Functor. I tried a couple different functional libraries, but I couldn't implement the desired behavior with any of the <code>zip</code>/<code>ap</code> methods that I tried.</p>
  <p>What I'm trying to do seems to me a fairly common operation that one might do with Optionals, and I realize that I could just write my own operator with the desired behavior. Still, I am wondering if there is a standard function/method in functional programming to achieve this common operation?</p>
  <p><strong>Update:</strong> I removed the <code>java</code> tag, as I'm curious how other languages handle this situation</p>