Question about Either.Projection.apply

Issue #38 resolved
Eric Patey created an issue

Not sure what the best way to ask a question in here is. Feel free to direct me to a more appropriate forum.

Can anyone point me to an example use of Either.Projection.apply?

I'm unclear on the use case and also confused by the fact that the input parameter is an Either rather than just the function.

Comments (3)

  1. Anund McKague

    Hi @epatey, Happy to help.

    Apply is a utility function for merging together an Either<A,B> with and an Either<A, Function<B,C>> to produce an Either<A,C>. As long as the left side type matches it applies the contained function to the original B to produce a C.

    Here's some contrived example code:

    public Either<Error, Function<String, Result>> buildMyFunction(int i) {
      if( i % 2 == 0 ){
         return right(evens); // a function that works on even integers
      } else {
         return left(error); // my magic error type
      }
    }
    
    public Either<Error, Result> dosomething(){
        // have an either from somewhere, here I'm building it inline, 
        return Either.<Error, String>right("my input") // notice the left type matches the result from buildMyFunction
           .right() // access the right projection
           .apply(buildMyFunction(some params)) // apply the function that can fail
    }
    

    If you have a naked function you could just call Either#map or Either#flatmap passing that function.

    Many of the functions on either are now right biased by default see https://bitbucket.org/atlassian/fugue/pull-requests/28/issue_32_right_biased_either_methods (it's in 2.3). Apply is not one of them.

    Additionally the apply function is slightly misnamed. Typically it would be called just ap. If you're interested in digging deeper you can define an Applicative for the either class given some additional constraints. The ap function on an applicative defines how you take a value inside a type like Either and combine it with a function also in an Either.

  2. Eric Patey reporter

    Thanks for the response. Your explanation makes sense.

    My comfort/facility level with functional stuff is at the fold/flatMap/map level. I can chain those bad boys together like a pro. I'm not yet there with stuff like this (applicatives, curried functions, etc). I'm still in the middle of a functional rewiring of my brain, so it's not yet intuitive for me. I appreciate the help.

    Eric

  3. Log in to comment