Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Map aliases #1315

Merged
merged 7 commits into from
Aug 7, 2019
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
24 changes: 16 additions & 8 deletions core/shared/src/main/scala/zio/ZIO.scala
Original file line number Diff line number Diff line change
Expand Up @@ -203,11 +203,8 @@ sealed trait ZIO[-R, +E, +A] extends Serializable { self =>

final def compose[R1, E1 >: E](that: ZIO[R1, E1, R]): ZIO[R1, E1, A] = self <<< that

/**
* Maps this effect to the specified constant while preserving the
* effects of this effect.
*/
final def const[B](b: => B): ZIO[R, E, B] = self.flatMap(new ZIO.ConstFn(() => b))
@deprecated("use as", "1.0.0")
final def const[B](b: => B): ZIO[R, E, B] = as(b)

/**
* Returns an effect that is delayed from this effect by the specified
Expand Down Expand Up @@ -470,6 +467,11 @@ sealed trait ZIO[-R, +E, +A] extends Serializable { self =>
*/
def map[B](f: A => B): ZIO[R, E, B] = new ZIO.FlatMap(self, new ZIO.MapFn(f))

/**
* Returns an effect whose success is replaced by the specified `b` value.
*/
final def as[B](b: B): ZIO[R, E, B] = self.flatMap(new ZIO.ConstFn(() => b))
ioleo marked this conversation as resolved.
Show resolved Hide resolved

/**
* Returns an effect with its error channel mapped using the specified
* function. This can be used to lift a "smaller" error into a "larger"
Expand All @@ -478,6 +480,12 @@ sealed trait ZIO[-R, +E, +A] extends Serializable { self =>
final def mapError[E2](f: E => E2): ZIO[R, E2, A] =
self.foldCauseM(new ZIO.MapErrorFn(f), new ZIO.SucceedFn(f))

/**
* Returns an effect whose error channel is replaced by the specified `e2` error.
* This can be used to lift a "smaller" error into a "larger" error.
*/
final def asError[E2](e2: E2): ZIO[R, E2, A] = mapError(_ => e2)
ioleo marked this conversation as resolved.
Show resolved Hide resolved

/**
* Returns an effect with its full cause of failure mapped using the
* specified function. This can be used to transform errors while
Expand Down Expand Up @@ -1242,7 +1250,7 @@ sealed trait ZIO[-R, +E, +A] extends Serializable { self =>
/**
* Returns the effect resulting from mapping the success of this effect to unit.
*/
final def unit: ZIO[R, E, Unit] = const(())
final def unit: ZIO[R, E, Unit] = as(())

/**
* The inverse operation to `sandbox`. Submerges the full cause of failure.
Expand Down Expand Up @@ -2459,7 +2467,7 @@ object ZIO extends ZIOFunctions {

final class ZipLeftFn[R, E, A, B](override val underlying: () => ZIO[R, E, A]) extends ZIOFn1[B, ZIO[R, E, B]] {
def apply(a: B): ZIO[R, E, B] =
underlying().const(a)
underlying().as(a)
}

final class ZipRightFn[R, E, A, B](override val underlying: () => ZIO[R, E, B]) extends ZIOFn1[A, ZIO[R, E, B]] {
Expand All @@ -2471,7 +2479,7 @@ object ZIO extends ZIOFunctions {

final class TapFn[R, E, A](override val underlying: A => ZIO[R, E, _]) extends ZIOFn1[A, ZIO[R, E, A]] {
def apply(a: A): ZIO[R, E, A] =
underlying(a).const(a)
underlying(a).as(a)
}

final class MapFn[R, E, A, B](override val underlying: A => B) extends ZIOFn1[A, ZIO[R, E, B]] {
Expand Down
22 changes: 11 additions & 11 deletions core/shared/src/main/scala/zio/ZManaged.scala
Original file line number Diff line number Diff line change
Expand Up @@ -224,11 +224,11 @@ final case class ZManaged[-R, +E, +A](reserve: ZIO[R, E, Reservation[R, E, A]])
Reservation(
acquire = for {
resR <- reserve
.flatMap(res => finalizers.update(res.release :: _).const(res))
.flatMap(res => finalizers.update(res.release :: _).as(res))
.uninterruptible
r <- resR.acquire
resR1 <- f0(r).reserve
.flatMap(res => finalizers.update(res.release :: _).const(res))
.flatMap(res => finalizers.update(res.release :: _).as(res))
.uninterruptible
r1 <- resR1.acquire
} yield r1,
Expand Down Expand Up @@ -301,19 +301,19 @@ final case class ZManaged[-R, +E, +A](reserve: ZIO[R, E, Reservation[R, E, A]])
val direct =
ZIO.uninterruptibleMask { restore =>
reserve
.flatMap(res => finalizers.update(res.release :: _).const(res))
.flatMap(res => finalizers.update(res.release :: _).as(res))
.flatMap(res => restore(res.acquire))
}
val onFailure = (e: E) =>
ZIO.uninterruptibleMask { restore =>
failure(e).reserve
.flatMap(res => finalizers.update(res.release :: _).const(res))
.flatMap(res => finalizers.update(res.release :: _).as(res))
.flatMap(res => restore(res.acquire))
}
val onSuccess = (a: A) =>
ZIO.uninterruptibleMask { restore =>
success(a).reserve
.flatMap(res => finalizers.update(res.release :: _).const(res))
.flatMap(res => finalizers.update(res.release :: _).as(res))
.flatMap(res => restore(res.acquire))
}
direct.foldM(onFailure, onSuccess)
Expand Down Expand Up @@ -594,7 +594,7 @@ final case class ZManaged[-R, +E, +A](reserve: ZIO[R, E, Reservation[R, E, A]])
)
)
.uninterruptible
cleanup.fork.const(None).uninterruptible
cleanup.fork.as(None).uninterruptible
}
)
}
Expand Down Expand Up @@ -709,12 +709,12 @@ final case class ZManaged[-R, +E, +A](reserve: ZIO[R, E, Reservation[R, E, A]])
acquire = {
val left = ZIO.uninterruptibleMask { restore =>
reserve
.flatMap(res => finalizers.update(fs => res.release :: fs).const(res))
.flatMap(res => finalizers.update(fs => res.release :: fs).as(res))
.flatMap(res => restore(res.acquire))
}
val right = ZIO.uninterruptibleMask { restore =>
that.reserve
.flatMap(res => finalizers.update(fs => res.release :: fs).const(res))
.flatMap(res => finalizers.update(fs => res.release :: fs).as(res))
.flatMap(res => restore(res.acquire))
}
left.zipWithPar(right)(f0)
Expand Down Expand Up @@ -1010,7 +1010,7 @@ object ZManaged {
case (a, prom) =>
ZIO.uninterruptibleMask { restore =>
a.reserve
.flatMap(res => finalizers.update(res.release :: _).const(res))
.flatMap(res => finalizers.update(res.release :: _).as(res))
.flatMap(res => restore(res.acquire))
}.foldCauseM(
_.failureOrCause.fold(prom.fail, prom.halt),
Expand Down Expand Up @@ -1088,7 +1088,7 @@ object ZManaged {
case (a, prom) =>
ZIO.uninterruptibleMask { restore =>
a.reserve
.flatMap(res => finalizers.update(res.release :: _).const(res))
.flatMap(res => finalizers.update(res.release :: _).as(res))
.flatMap(res => restore(res.acquire))
}.foldCauseM(
_.failureOrCause.fold(prom.fail, prom.halt),
Expand All @@ -1106,7 +1106,7 @@ object ZManaged {
}
zero = ZIO.uninterruptibleMask { restore =>
a1.reserve
.flatMap(res => finalizers.update(res.release :: _).const(res))
.flatMap(res => finalizers.update(res.release :: _).as(res))
.flatMap(res => restore(res.acquire))
}
result <- proms.foldLeft[ZIO[R, E, A]](zero) { (acc, a) =>
Expand Down
11 changes: 7 additions & 4 deletions core/shared/src/main/scala/zio/ZSchedule.scala
Original file line number Diff line number Diff line change
Expand Up @@ -232,10 +232,13 @@ trait ZSchedule[-R, -A, +B] extends Serializable { self =>
*/
final def compose[R1 <: R, C](that: ZSchedule[R1, C, A]): ZSchedule[R1, C, B] = self <<< that

@deprecated("use as", "1.0.0")
final def const[C](c: => C): ZSchedule[R, A, C] = as(c)

/**
* Returns a new schedule that maps this schedule to a constant output.
*/
final def const[C](c: => C): ZSchedule[R, A, C] = map(_ => c)
final def as[C](c: => C): ZSchedule[R, A, C] = map(_ => c)

/**
* Returns a new schedule that deals with a narrower class of inputs than
Expand Down Expand Up @@ -476,7 +479,7 @@ trait ZSchedule[-R, -A, +B] extends Serializable { self =>
/**
* Returns a new schedule that maps this schedule to a Unit output.
*/
final def unit: ZSchedule[R, A, Unit] = const(())
final def unit: ZSchedule[R, A, Unit] = as(())

/**
* Returns a new schedule that continues the schedule only until the predicate
Expand Down Expand Up @@ -722,12 +725,12 @@ object ZSchedule {
/**
* A schedule that recurs forever, returning the constant for every output.
*/
final def succeed[A](a: A): Schedule[Any, A] = forever.const(a)
final def succeed[A](a: A): Schedule[Any, A] = forever.as(a)

/**
* A schedule that recurs forever, returning the constant for every output (by-name version).
*/
final def succeedLazy[A](a: => A): Schedule[Any, A] = forever.const(a)
final def succeedLazy[A](a: => A): Schedule[Any, A] = forever.as(a)

/**
* A schedule that always recurs without delay, and computes the output
Expand Down
2 changes: 1 addition & 1 deletion docs/datatypes/io.md
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,7 @@ object Main extends App {

// run my bracket
def run(args: List[String]) =
mybracket.orDie.const(0)
mybracket.orDie.as(0)

def closeStream(is: FileInputStream) =
UIO(is.close())
Expand Down
8 changes: 4 additions & 4 deletions streams-tests/jvm/src/test/scala/zio/stream/SinkSpec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -346,22 +346,22 @@ class SinkSpec(implicit ee: org.specs2.concurrent.ExecutionEnv)
}

private def constHappyPath = {
val sink = ZSink.identity[Int].const("const")
val sink = ZSink.identity[Int].as("const")
unsafeRun(sinkIteration(sink, 1).map(_ must_=== "const"))
}

private def constInitError = {
val sink = initErrorSink.const("const")
val sink = initErrorSink.as("const")
unsafeRun(sinkIteration(sink, 1).either.map(_ must_=== Left("Ouch")))
}

private def constStepError = {
val sink = stepErrorSink.const("const")
val sink = stepErrorSink.as("const")
unsafeRun(sinkIteration(sink, 1).either.map(_ must_=== Left("Ouch")))
}

private def constExtractError = {
val sink = extractErrorSink.const("const")
val sink = extractErrorSink.as("const")
unsafeRun(sinkIteration(sink, 1).either.map(_ must_=== Left("Ouch")))
}

Expand Down
6 changes: 3 additions & 3 deletions streams-tests/jvm/src/test/scala/zio/stream/StreamSpec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -770,7 +770,7 @@ class ZStreamSpec(implicit ee: org.specs2.concurrent.ExecutionEnv)
inner = Stream
.bracket(execution.update("InnerAcquire" :: _))(_ => execution.update("InnerRelease" :: _))
_ <- Stream
.bracket(execution.update("OuterAcquire" :: _).const(inner))(_ => execution.update("OuterRelease" :: _))
.bracket(execution.update("OuterAcquire" :: _).as(inner))(_ => execution.update("OuterRelease" :: _))
.flatMapPar(2)(identity)
.runDrain
results <- execution.get
Expand Down Expand Up @@ -892,7 +892,7 @@ class ZStreamSpec(implicit ee: org.specs2.concurrent.ExecutionEnv)
execution <- Ref.make(List.empty[String])
inner = Stream.bracket(execution.update("InnerAcquire" :: _))(_ => execution.update("InnerRelease" :: _))
_ <- Stream
.bracket(execution.update("OuterAcquire" :: _).const(inner))(_ => execution.update("OuterRelease" :: _))
.bracket(execution.update("OuterAcquire" :: _).as(inner))(_ => execution.update("OuterRelease" :: _))
.flatMapParSwitch(2)(identity)
.runDrain
results <- execution.get
Expand Down Expand Up @@ -1421,7 +1421,7 @@ class ZStreamSpec(implicit ee: org.specs2.concurrent.ExecutionEnv)
val stream = ZStream(1, 2, 3, 4)
val test = for {
resource <- Ref.make(0)
sink = ZManaged.make(resource.set(1000).const(new TestSink(resource)))(_ => resource.set(2000))
sink = ZManaged.make(resource.set(1000).as(new TestSink(resource)))(_ => resource.set(2000))
result <- stream.transduceManaged(sink).runCollect
i <- resource.get
_ <- if (i != 2000) IO.fail(new IllegalStateException(i.toString)) else IO.unit
Expand Down
7 changes: 5 additions & 2 deletions streams/shared/src/main/scala/zio/stream/ZSink.scala
Original file line number Diff line number Diff line change
Expand Up @@ -263,10 +263,13 @@ trait ZSink[-R, +E, +A0, -A, +B] { self =>
def extract(state: State): ZIO[R1, E1, B] = self.extract(state)
}

@deprecated("use as", "1.0.0")
final def const[C](c: => C): ZSink[R, E, A0, A, C] = as(c)

/**
* Creates a sink that always produces `c`
*/
final def const[C](c: => C): ZSink[R, E, A0, A, C] = self.map(_ => c)
final def as[C](c: => C): ZSink[R, E, A0, A, C] = self.map(_ => c)

/**
* Creates a sink that transforms entering values with `f` and
Expand Down Expand Up @@ -698,7 +701,7 @@ trait ZSink[-R, +E, +A0, -A, +B] { self =>
/**
* Creates a sink that ignores all produced elements.
*/
final def unit: ZSink[R, E, A0, A, Unit] = const(())
final def unit: ZSink[R, E, A0, A, Unit] = as(())

/**
* Creates a sink that produces values until one verifies
Expand Down
20 changes: 10 additions & 10 deletions streams/shared/src/main/scala/zio/stream/ZStream.scala
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ trait ZStream[-R, +E, +A] extends Serializable { self =>
for {
s <- ref.get
a <- f(s).flatMap {
case (a, s2) => ref.set(s2).const(a)
case (a, s2) => ref.set(s2).as(a)
}
} yield a
}
Expand All @@ -104,7 +104,7 @@ trait ZStream[-R, +E, +A] extends Serializable { self =>
result <- if (Step.cont(step))
UIO.succeed(
// Notify the consumer so they won't busy wait
(notifyConsumer.succeed(()).const(true), State.BatchMiddle(Step.state(step), notifyProducer))
(notifyConsumer.succeed(()).as(true), State.BatchMiddle(Step.state(step), notifyProducer))
)
else
UIO.succeed(
Expand Down Expand Up @@ -138,7 +138,7 @@ trait ZStream[-R, +E, +A] extends Serializable { self =>

// The producer shouldn't actually see these states, but we still use sane
// transitions here anyway.
case s @ State.BatchEnd(_, batchTaken) => UIO.succeed((batchTaken.await.const(true), s))
case s @ State.BatchEnd(_, batchTaken) => UIO.succeed((batchTaken.await.as(true), s))
case State.Error(e) => ZIO.halt(e)
case State.End => UIO.succeed((UIO.succeed(true), State.End))
}.flatten
Expand All @@ -147,7 +147,7 @@ trait ZStream[-R, +E, +A] extends Serializable { self =>
def consume(stateVar: Ref[State], permits: Semaphore): ZIO[R1, E1, Option[Chunk[B]]] =
withStateVar(stateVar, permits) {
// If the state is empty, wait for a notification from the producer
case s @ State.Empty(_, notify) => UIO.succeed((notify.await.const(Some(Chunk.empty)), s))
case s @ State.Empty(_, notify) => UIO.succeed((notify.await.as(Some(Chunk.empty)), s))

case State.BatchMiddle(state, notifyProducer) =>
for {
Expand Down Expand Up @@ -266,7 +266,7 @@ trait ZStream[-R, +E, +A] extends Serializable { self =>
for {
s <- ref.get
a <- f(s).flatMap {
case (a, s2) => ref.set(s2).const(a)
case (a, s2) => ref.set(s2).as(a)
}
} yield a
}
Expand Down Expand Up @@ -319,7 +319,7 @@ trait ZStream[-R, +E, +A] extends Serializable { self =>

// The producer shouldn't actually see these states, but we do whatever is sensible anyway
case s @ State.BatchEnd(_, notifyProducer) =>
UIO.succeed(notifyProducer.await.const(true) -> s)
UIO.succeed(notifyProducer.await.as(true) -> s)

case s @ State.Error(c) =>
UIO.succeed(ZIO.halt(c) -> s)
Expand Down Expand Up @@ -368,7 +368,7 @@ trait ZStream[-R, +E, +A] extends Serializable { self =>
s = State.Empty(sinkInitial, notifyConsumer)
action = notifyProducer
.succeed(())
.const(
.as(
Some(
Chunk
.single(Right(batch)) -> UnfoldState(Some(batch), decision.state, notifyConsumer)
Expand All @@ -385,7 +385,7 @@ trait ZStream[-R, +E, +A] extends Serializable { self =>
s = State.Empty(sinkInitial, notifyConsumer)
action = notifyProducer
.succeed(())
.const(
.as(
Some(
Chunk
.single(Right(batch)) -> UnfoldState(Some(batch), decision.state, notifyConsumer)
Expand Down Expand Up @@ -791,14 +791,14 @@ trait ZStream[-R, +E, +A] extends Serializable { self =>
* Consumes all elements of the stream, passing them to the specified callback.
*/
final def foreach[R1 <: R, E1 >: E](f: A => ZIO[R1, E1, Unit]): ZIO[R1, E1, Unit] =
foreachWhile(f.andThen(_.const(true)))
foreachWhile(f.andThen(_.as(true)))

/**
* Like [[ZStream#foreach]], but returns a `ZManaged` so the finalization order
* can be controlled.
*/
final def foreachManaged[R1 <: R, E1 >: E](f: A => ZIO[R1, E1, Unit]): ZManaged[R1, E1, Unit] =
foreachWhileManaged(f.andThen(_.const(true)))
foreachWhileManaged(f.andThen(_.as(true)))

/**
* Consumes elements of the stream, passing them to the specified callback,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ trait ZStreamChunk[-R, +E, @specialized +A] { self =>
* Consumes all elements of the stream, passing them to the specified callback.
*/
final def foreach[R1 <: R, E1 >: E](f: A => ZIO[R1, E1, Unit]): ZIO[R1, E1, Unit] =
foreachWhile[R1, E1](f(_).const(true))
foreachWhile[R1, E1](f(_).as(true))

/**
* Consumes elements of the stream, passing them to the specified callback,
Expand Down