Compose ReaderT with Either through for-comprehension and applicative pureApplicatives compose, monads don'tEither, Options and for comprehensionsWhat's the best way to get a Scala Object field by inputting Object name in StringParser combinator optional partsFor Comprehension Example to Understand Composing MonadsApplicative <*> inside ReaderT StateT IOHow to compose functions operating with ReaderT and Either?For comprehensions Future and EitherCompose optional queries for for-comprehension in doobie?Scala - How to Combine EitherT with Either in For Comprehension

How might a landlocked lake become a complete ecosystem?

Where to find every-day healthy food near Heathrow Airport?

Do Life Drain attacks from wights stack?

Motorola 6845 and bitwise graphics

Is 95% of what you read in the financial press “either wrong or irrelevant?”

Were any toxic metals used in the International Space Station?

How can we allow remote players to effectively interact with a physical tabletop battle-map?

Why does lemon juice reduce the "fish" odor of sea food — specifically fish?

Could there be a material that inverts the colours seen through it?

What information do scammers need to withdraw money from an account?

Why doesn't Iron Man's action affect this person in Endgame?

Adding labels and comments to a matrix

Is this possible when it comes to the relations of P, NP, NP-Hard and NP-Complete?

Substring join or additional table, which is faster?

Are there any established rules for splitting books into parts, chapters, sections etc?

How do I adjust encounters to challenge my lycanthrope players without negating their cool new abilities?

complicated arrows in flowcharts

Can a tourist shoot a gun for recreational purpose in the USA?

Is 12 minutes connection in Bristol Temple Meads long enough?

Why does the headset man not get on the tractor?

Alexa-rank complaining about insecure generator meta-tag

What was Euron's motivation for this fight in "The Bells"?

Can you pick an advanced rogue talent with the extra rogue talent feat?

Fixed width with p doesn't work



Compose ReaderT with Either through for-comprehension and applicative pure


Applicatives compose, monads don'tEither, Options and for comprehensionsWhat's the best way to get a Scala Object field by inputting Object name in StringParser combinator optional partsFor Comprehension Example to Understand Composing MonadsApplicative <*> inside ReaderT StateT IOHow to compose functions operating with ReaderT and Either?For comprehensions Future and EitherCompose optional queries for for-comprehension in doobie?Scala - How to Combine EitherT with Either in For Comprehension






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








1















Here are functions that return ReaderT and Either as a return type:



 import cats.data.ReaderT
type FailFast[A] = Either[List[String], A]

def getValue(name: String):ReaderT[FailFast, Map[String, String], String] =
ReaderT((map) => map.get(name)
.toRight(List(s"$name field not specified")))

def nonNullable(name: String)(data: String): FailFast[String] =
Right(data).ensure(List(s"$name cannot be nullable"))(_ != null)

def nonBlank(name: String)(data: String): FailFast[String] =
Right(data).ensure(List(s"$name cannot be blank"))(_.nonEmpty)


Here is a composition of these functions that works fine:



 def readNotEmptyValue(name: String): ReaderT[FailFast, Map[String, String], String] =
for
value <- getValue(name)
_ <- ReaderT((_:Map[String, String]) => nonNullable(name)(value))
res <- ReaderT((_:Map[String, String]) => nonBlank(name)(value))
yield res


I want to get rid of this ReaderT.apply invocation, and write something via applicative pure:



 type Q[A] = ReaderT[FailFast, Map[String, String], A]
import cats.syntax.applicative._
import cats.instances.either._
def readNotEmptyValue(name: String): ReaderT[FailFast, Map[String, String], String] =
for
value <- getValue(name)
_ <- nonBlank(name)(value).pure[Q]
res <- nonBlank(name)(value).pure[Q]
yield res.right.get


Unfortunately the last solution does not work with negative cases. I can for sure use match to check, weather it is Right or Left.



But is there a way to compose it with pure and minimize manual effort. How to do it correctly?










share|improve this question




























    1















    Here are functions that return ReaderT and Either as a return type:



     import cats.data.ReaderT
    type FailFast[A] = Either[List[String], A]

    def getValue(name: String):ReaderT[FailFast, Map[String, String], String] =
    ReaderT((map) => map.get(name)
    .toRight(List(s"$name field not specified")))

    def nonNullable(name: String)(data: String): FailFast[String] =
    Right(data).ensure(List(s"$name cannot be nullable"))(_ != null)

    def nonBlank(name: String)(data: String): FailFast[String] =
    Right(data).ensure(List(s"$name cannot be blank"))(_.nonEmpty)


    Here is a composition of these functions that works fine:



     def readNotEmptyValue(name: String): ReaderT[FailFast, Map[String, String], String] =
    for
    value <- getValue(name)
    _ <- ReaderT((_:Map[String, String]) => nonNullable(name)(value))
    res <- ReaderT((_:Map[String, String]) => nonBlank(name)(value))
    yield res


    I want to get rid of this ReaderT.apply invocation, and write something via applicative pure:



     type Q[A] = ReaderT[FailFast, Map[String, String], A]
    import cats.syntax.applicative._
    import cats.instances.either._
    def readNotEmptyValue(name: String): ReaderT[FailFast, Map[String, String], String] =
    for
    value <- getValue(name)
    _ <- nonBlank(name)(value).pure[Q]
    res <- nonBlank(name)(value).pure[Q]
    yield res.right.get


    Unfortunately the last solution does not work with negative cases. I can for sure use match to check, weather it is Right or Left.



    But is there a way to compose it with pure and minimize manual effort. How to do it correctly?










    share|improve this question
























      1












      1








      1








      Here are functions that return ReaderT and Either as a return type:



       import cats.data.ReaderT
      type FailFast[A] = Either[List[String], A]

      def getValue(name: String):ReaderT[FailFast, Map[String, String], String] =
      ReaderT((map) => map.get(name)
      .toRight(List(s"$name field not specified")))

      def nonNullable(name: String)(data: String): FailFast[String] =
      Right(data).ensure(List(s"$name cannot be nullable"))(_ != null)

      def nonBlank(name: String)(data: String): FailFast[String] =
      Right(data).ensure(List(s"$name cannot be blank"))(_.nonEmpty)


      Here is a composition of these functions that works fine:



       def readNotEmptyValue(name: String): ReaderT[FailFast, Map[String, String], String] =
      for
      value <- getValue(name)
      _ <- ReaderT((_:Map[String, String]) => nonNullable(name)(value))
      res <- ReaderT((_:Map[String, String]) => nonBlank(name)(value))
      yield res


      I want to get rid of this ReaderT.apply invocation, and write something via applicative pure:



       type Q[A] = ReaderT[FailFast, Map[String, String], A]
      import cats.syntax.applicative._
      import cats.instances.either._
      def readNotEmptyValue(name: String): ReaderT[FailFast, Map[String, String], String] =
      for
      value <- getValue(name)
      _ <- nonBlank(name)(value).pure[Q]
      res <- nonBlank(name)(value).pure[Q]
      yield res.right.get


      Unfortunately the last solution does not work with negative cases. I can for sure use match to check, weather it is Right or Left.



      But is there a way to compose it with pure and minimize manual effort. How to do it correctly?










      share|improve this question














      Here are functions that return ReaderT and Either as a return type:



       import cats.data.ReaderT
      type FailFast[A] = Either[List[String], A]

      def getValue(name: String):ReaderT[FailFast, Map[String, String], String] =
      ReaderT((map) => map.get(name)
      .toRight(List(s"$name field not specified")))

      def nonNullable(name: String)(data: String): FailFast[String] =
      Right(data).ensure(List(s"$name cannot be nullable"))(_ != null)

      def nonBlank(name: String)(data: String): FailFast[String] =
      Right(data).ensure(List(s"$name cannot be blank"))(_.nonEmpty)


      Here is a composition of these functions that works fine:



       def readNotEmptyValue(name: String): ReaderT[FailFast, Map[String, String], String] =
      for
      value <- getValue(name)
      _ <- ReaderT((_:Map[String, String]) => nonNullable(name)(value))
      res <- ReaderT((_:Map[String, String]) => nonBlank(name)(value))
      yield res


      I want to get rid of this ReaderT.apply invocation, and write something via applicative pure:



       type Q[A] = ReaderT[FailFast, Map[String, String], A]
      import cats.syntax.applicative._
      import cats.instances.either._
      def readNotEmptyValue(name: String): ReaderT[FailFast, Map[String, String], String] =
      for
      value <- getValue(name)
      _ <- nonBlank(name)(value).pure[Q]
      res <- nonBlank(name)(value).pure[Q]
      yield res.right.get


      Unfortunately the last solution does not work with negative cases. I can for sure use match to check, weather it is Right or Left.



      But is there a way to compose it with pure and minimize manual effort. How to do it correctly?







      scala monads composition monad-transformers scala-cats






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Mar 23 at 13:56









      AlexandrAlexandr

      5,02784581




      5,02784581






















          1 Answer
          1






          active

          oldest

          votes


















          2














          Instead of Applicative.pure, you can use EitherOps.liftTo to remove the verboseness of ReaderT.apply:



          def readNotEmptyValue(name: String): ReaderT[FailFast, Map[String, String], String] = 
          for
          value <- getValue(name)
          _ <- nonBlank(name)(value).liftTo[Q]
          res <- nonBlank(name)(value).liftTo[Q]
          yield res


          Otherwise, you're still dealing with an instance of FailFast[String] and not String, and there's no way around it if you want to attempt and extract the value out of FailFast.






          share|improve this answer

























            Your Answer






            StackExchange.ifUsing("editor", function ()
            StackExchange.using("externalEditor", function ()
            StackExchange.using("snippets", function ()
            StackExchange.snippets.init();
            );
            );
            , "code-snippets");

            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "1"
            ;
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function()
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled)
            StackExchange.using("snippets", function()
            createEditor();
            );

            else
            createEditor();

            );

            function createEditor()
            StackExchange.prepareEditor(
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader:
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            ,
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            );



            );













            draft saved

            draft discarded


















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55314431%2fcompose-readert-with-either-through-for-comprehension-and-applicative-pure%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            2














            Instead of Applicative.pure, you can use EitherOps.liftTo to remove the verboseness of ReaderT.apply:



            def readNotEmptyValue(name: String): ReaderT[FailFast, Map[String, String], String] = 
            for
            value <- getValue(name)
            _ <- nonBlank(name)(value).liftTo[Q]
            res <- nonBlank(name)(value).liftTo[Q]
            yield res


            Otherwise, you're still dealing with an instance of FailFast[String] and not String, and there's no way around it if you want to attempt and extract the value out of FailFast.






            share|improve this answer





























              2














              Instead of Applicative.pure, you can use EitherOps.liftTo to remove the verboseness of ReaderT.apply:



              def readNotEmptyValue(name: String): ReaderT[FailFast, Map[String, String], String] = 
              for
              value <- getValue(name)
              _ <- nonBlank(name)(value).liftTo[Q]
              res <- nonBlank(name)(value).liftTo[Q]
              yield res


              Otherwise, you're still dealing with an instance of FailFast[String] and not String, and there's no way around it if you want to attempt and extract the value out of FailFast.






              share|improve this answer



























                2












                2








                2







                Instead of Applicative.pure, you can use EitherOps.liftTo to remove the verboseness of ReaderT.apply:



                def readNotEmptyValue(name: String): ReaderT[FailFast, Map[String, String], String] = 
                for
                value <- getValue(name)
                _ <- nonBlank(name)(value).liftTo[Q]
                res <- nonBlank(name)(value).liftTo[Q]
                yield res


                Otherwise, you're still dealing with an instance of FailFast[String] and not String, and there's no way around it if you want to attempt and extract the value out of FailFast.






                share|improve this answer















                Instead of Applicative.pure, you can use EitherOps.liftTo to remove the verboseness of ReaderT.apply:



                def readNotEmptyValue(name: String): ReaderT[FailFast, Map[String, String], String] = 
                for
                value <- getValue(name)
                _ <- nonBlank(name)(value).liftTo[Q]
                res <- nonBlank(name)(value).liftTo[Q]
                yield res


                Otherwise, you're still dealing with an instance of FailFast[String] and not String, and there's no way around it if you want to attempt and extract the value out of FailFast.







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Mar 23 at 15:00

























                answered Mar 23 at 14:45









                Yuval ItzchakovYuval Itzchakov

                118k26179248




                118k26179248





























                    draft saved

                    draft discarded
















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid …


                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.

                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function ()
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55314431%2fcompose-readert-with-either-through-for-comprehension-and-applicative-pure%23new-answer', 'question_page');

                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    How to preserve electronics (computers, tablets and phones) for hundreds of years Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) The network's official Twitter account is up and running again. What content…How might modern humans leave a message for 50,000 years?How would an aquatic race develop computers?How do we make computers care for human life?Keeping supplies for 1000 yearsWhat will cell phones become in 100 years?What body armor protects against a laser?Could a society attain 1800s technology if limited to using copper and bronze?Electricity power (magic) and electronicsScavenging metal resources in post-apocalypse after 100 yearsWhy would precursors create devices that can survive and still work after hundreds of years?

                    155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해

                    Convert JSON to MapSimplest way to convert a string representing JSON array into Java array List of key value pairsHow to take String JSON values into HashMapConvert a JSON String to a HashMapCreating BSON object from JSON stringJSONObject - How to get a value ?Better Map ConstructorReading JSON from Url javaUpdate columns if input values are not null otherwise ignore and keep the existing values of column in databaseHow to store object represented as Json string into Couchbase Lite?Go JSON into MapHow do I efficiently iterate over each entry in a Java Map?Sort a Map<Key, Value> by valuesHow to round a number to n decimal places in JavaCan comments be used in JSON?How do I read / convert an InputStream into a String in Java?How can I pretty-print JSON in a shell script?What is the correct JSON content type?How can I deserialize JSON to a simple Dictionary<string,string> in ASP.NET?Why does Google prepend while(1); to their JSON responses?Parse JSON in JavaScript?