Scala Reader Fashion: Return, Local, and Consistency

I use the monad Readerin Scala provided by the scalaz library . I am familiar with this monad as defined in Haskell . The problem is that I cannot find functions equivalent returnto localand sequence(among other things).

I am currently using constructs that I don't like, as I am repeating myself or making my code a bit obscure.

As for return, I am currently using:

Reader{_ => someValue}

I would just use a type construct unit(someValue), but I could not find anything on the Internet. There are textbooks like this one that use the above approach and which I consider not optimal.

Regarding, localI also need to do something similar: instead of entering something like: local f myReaderI need to expand its definition:

Reader{env => myReader.run(f(env))

Finally, the sequence is a little closer to what I expect (as a Haskell refugee doing Scala):

readers: List[Reader[Env, T]]
readerTs: Reader[Env, List[T]] = readers.sequenceU

My problem with this implementation is that, being relatively new to Scala, the type sequenceU

final class TraverseOps[F[_],A] private[syntax](val self: F[A])(implicit val F: Traverse[F]) extends Ops[F[A]] {
    //...
    def sequenceU(implicit G: Unapply[Applicative, A]): G.M[F[G.A]]

looks rather obscure and seems like black magic. Ideally, I would like to use operations sequencein Monads.

Is there a better translation of these constructions into Scala, available on a scalar or similar library? I am not married to any functional library for Scala, so any solution using other libraries will do, although I would prefer to get the answer using scalaz, since I already used my code using it.

+4
1

, . defs - . ReaderInt, lambdas.

return/pure/point

Scala , . Kleisli ( ) Kleisli[Id, ?, ?]

 implicit val KA = scalaz.Kleisli.kleisliIdApplicative[Int]
 type ReaderInt[A] = Kleisli[Id.Id, Int, A]

 val alwaysHello = KA.point("hello")  

:

  import scalaz.syntax.applicative._  
  val alwaysHello = "hello".point[ReaderInt]

, ,

1) , scalaz.std.something.somethingInstance

2) import scalaz.syntax.something._

3), x.point[F], F .

, , Kleisli local.

val f: String ⇒ Int = _.length
val alwaysEleven = alwaysHello local f

syntax .

  import scalaz.std.list.listInstance
  val initial: List[ReaderInt[String]] = ???  
  val sequenced: ReaderInt[List[String]] = Traverse[List].sequence[ReaderInt, String](initial) 

  import scalaz.syntax.traverse._
  val z = x.sequence[ReaderInt, String]    

sequenceU, Unapply typelcass G, scala . , .

, cats, .

+1

Source: https://habr.com/ru/post/1648766/


All Articles