Question: I have a function in a context, (in a Maybe / Option) and I want to pass it a value and get back the return value, directly out of the context.

Let's take an example in Scala :

```
scala> Some((x:Int) => x * x)
res0: Some[Int => Int] = Some(<function1>)

```

Of course, I can do

```
res0.map(_(5))

```

to execute the function, but the result is wrapped in the context.

Ok, I could do :

```
res0.map(_(5)).getOrElse(...)

```

but I'm copy/pasting this everywhere in my code (I have a lot of functions wrapped in Option, or worst, in Either...).

I need a better form, something like :

```
res0.applyOrElse(5, ...)

```

Does this concept of 'applying a function in a concept to a value and immediatly returning the result out of the context' exists in FP with a specific name (I'm lost in all those Functor, Monad and Applicatives...) ?

Answer: 
You could write something like `applyOrElse` using `Option.fold`.

> 
> fold[B](ifEmpty: ⇒ B)(f: (A) ⇒ B): B 
> 
> 
> 

```
val squared = Some((x:Int) => x * x)
squared.fold { 
  // or else = ifEmpty
  math.pow(5, 2).toInt
}{
  // execute function
  _(5)
}

```

---

Using Travis Browns recent [answer](https://stackoverflow.com/questions/31481836/scala-function-tupled-and-function-untupled-equivalent-for-variable-arity-or-c/31485711#31485711) on another question, I was able to puzzle together the following `applyOrElse` function. It depends on Shapeless and you need to pass the arguments as an `HList` so it might not be exactly what you want.

```
def applyOrElse[F, I <: HList, O](
  optionFun: Option[F],
  input: I,
  orElse: => O
)(implicit
  ftp: FnToProduct.Aux[F, I => O]
): O = optionFun.fold(orElse)(f => ftp(f)(input))

```

Which can be used as :

```
val squared = Some((x:Int) => x * x)
applyOrElse(squared, 2 :: HNil, 10)
// res0: Int = 4

applyOrElse(None, 2 :: HNil, 10)
// res1: Int = 10

val concat = Some((a: String, b: String) => s"$a $b")
applyOrElse(concat, "hello" :: "world" :: HNil, "not" + "executed")
// res2: String = hello world

```
The getOrElse is most logical way to do it. In regards to copy/pasting it all over the place - you might not be dividing your logic up on the best way. Generally, you want to defer resolving your Options (or Futures/etc) in your code until the point you need to have it unwrapped. In this case, it seems more sensible that your function takes in an an Int and returns an Int, and you map your option where you need the result of that function.