scala.language.higherKinds Scala Examples
The following examples show how to use scala.language.higherKinds.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
Example 1
Source File: akkaStreams.scala From sangria-akka-streams with Apache License 2.0 | 5 votes |
package sangria.streaming import scala.language.higherKinds import akka.NotUsed import akka.event.Logging import akka.stream.ActorAttributes.SupervisionStrategy import akka.stream._ import akka.stream.scaladsl.{Merge, Sink, Source} import akka.stream.stage.{GraphStage, GraphStageLogic, InHandler, OutHandler} import scala.concurrent.Future object akkaStreams { type AkkaSource[+T] = Source[T, NotUsed] abstract class SimpleLinearGraphStage[T] extends GraphStage[FlowShape[T, T]] { val in = Inlet[T](Logging.simpleName(this) + ".in") val out = Outlet[T](Logging.simpleName(this) + ".out") override val shape = FlowShape(in, out) } class AkkaStreamsSubscriptionStream(implicit materializer: Materializer) extends SubscriptionStream[AkkaSource] { def supported[T[_]](other: SubscriptionStream[T]) = other.isInstanceOf[AkkaStreamsSubscriptionStream] def map[A, B](source: AkkaSource[A])(fn: A => B) = source.map(fn) def singleFuture[T](value: Future[T]) = Source.fromFuture(value) def single[T](value: T) = Source.single(value) def mapFuture[A, B](source: AkkaSource[A])(fn: A => Future[B]) = source.mapAsync(1)(fn) def first[T](s: AkkaSource[T]) = s.runWith(Sink.head) def failed[T](e: Throwable) = Source.failed(e).asInstanceOf[AkkaSource[T]] def onComplete[Ctx, Res](result: AkkaSource[Res])(op: => Unit) = result .via(OnComplete(() => op)) .recover {case e => op; throw e} .asInstanceOf[AkkaSource[Res]] def flatMapFuture[Ctx, Res, T](future: Future[T])(resultFn: T => AkkaSource[Res]) = Source.fromFuture(future).flatMapMerge(1, resultFn) def merge[T](streams: Vector[AkkaSource[T]]) = { if (streams.size > 1) Source.combine(streams(0), streams(1), streams.drop(2): _*)(Merge(_)) else if (streams.nonEmpty) streams.head else throw new IllegalStateException("No streams produced!") } def recover[T](stream: AkkaSource[T])(fn: Throwable => T) = stream recover {case e => fn(e)} } implicit def akkaSubscriptionStream(implicit materializer: Materializer): SubscriptionStream[AkkaSource] = new AkkaStreamsSubscriptionStream implicit def akkaStreamIsValidSubscriptionStream[A[_, _], Ctx, Res, Out](implicit materializer: Materializer, ev1: ValidOutStreamType[Res, Out]): SubscriptionStreamLike[Source[A[Ctx, Res], NotUsed], A, Ctx, Res, Out] = new SubscriptionStreamLike[Source[A[Ctx, Res], NotUsed], A, Ctx, Res, Out] { type StreamSource[X] = AkkaSource[X] val subscriptionStream = new AkkaStreamsSubscriptionStream } private final case class OnComplete[T](op: () => Unit) extends SimpleLinearGraphStage[T] { override def toString: String = "OnComplete" override def createLogic(inheritedAttributes: Attributes): GraphStageLogic = new GraphStageLogic(shape) with OutHandler with InHandler { def decider = inheritedAttributes.get[SupervisionStrategy].map(_.decider).getOrElse(Supervision.stoppingDecider) override def onPush(): Unit = { push(out, grab(in)) } override def onPull(): Unit = pull(in) override def onDownstreamFinish() = { op() super.onDownstreamFinish() } override def onUpstreamFinish() = { op() super.onUpstreamFinish() } setHandlers(in, out, this) } } }
Example 2
Source File: thunk.scala From Scala-High-Performance-Programming with MIT License | 5 votes |
package highperfscala.free import scala.language.{higherKinds, implicitConversions, postfixOps} import scalaz.{-\/, Free, Functor, \/, \/-} case class LimitMs(value: Long) extends AnyVal sealed trait Thunk[A] case class Timed[A]( whenActive: () => A, whenExpired: () => A, limit: LimitMs) extends Thunk[A] case class StartProcessing[A]( whenActive: BboUpdated => A, whenExpired: BboUpdated => A, limit: LimitMs) extends Thunk[A] case class TradingDecision[A]( makeDecision: TradingStrategy => A) extends Thunk[A] object Thunk { implicit val functor: Functor[Thunk] = new Functor[Thunk] { def map[A, B](t: Thunk[A])(f: (A) => B): Thunk[B] = t match { case Timed(whenActive, whenExpired, limit) => Timed(() => f(whenActive()), () => f(whenExpired()), limit) case StartProcessing(whenActive, whenExpired, limit) => StartProcessing(c => f(whenActive(c)), c => f(whenExpired(c)), limit) case TradingDecision(makeDecision) => TradingDecision( (makeDecision.apply _).andThen(f)) } } def timed[L, R]( f: () => R, exp: () => L, limit: LimitMs): Free[Thunk, L \/ R] = Free.liftF( Timed(() => \/-(f()), () => -\/(exp()), limit)) def startProcessing[L, R]( f: BboUpdated => R, exp: BboUpdated => L, limit: LimitMs): Free[Thunk, L \/ R] = Free.liftF(StartProcessing(f.andThen(\/-(_)), exp.andThen(-\/(_)), limit)) def tradingDecision[L, R](f: TradingStrategy => R): Free[Thunk, L \/ R] = Free.liftF(TradingDecision((f.apply _).andThen(\/-(_)))) }
Example 3
Source File: JsonApiInstances.scala From jsonapi-scala with BSD 3-Clause "New" or "Revised" License | 5 votes |
package com.qvantel.jsonapi.client.http4s import scala.language.higherKinds import cats._ import cats.effect._ import cats.implicits._ import cats.data._ import org.http4s._ import org.http4s.headers.`Content-Type` import spray.json._ import com.qvantel.jsonapi.{JsonApiReader, JsonApiWriter, readCollection, readOne, rawOne, rawCollection} final case class Include(include: Set[String]) trait JsonApiInstances extends JsonApiInstancesLowPrio { implicit def jsonapiJsObjectDecoder[F[_]: Effect](implicit include: Include): EntityDecoder[F, JsObject] = EntityDecoder.decodeBy(mediaType) { msg: Message[F] => EitherT { msg.as[String].map(s => s.parseJson.asJsObject.asRight[DecodeFailure]) } } implicit def jsonapiDecoder[F[_]: Effect, A: JsonApiReader](implicit include: Include): EntityDecoder[F, A] = EntityDecoder.decodeBy(mediaType) { msg: Message[F] => EitherT { msg.as[JsObject].map(json => readOne[A](json, include.include).asRight[DecodeFailure]) } } implicit def jsonapiListDecoder[F[_]: Effect, A: JsonApiReader]( implicit include: Include): EntityDecoder[F, List[A]] = EntityDecoder.decodeBy(mediaType) { msg: Message[F] => EitherT { msg.as[JsObject].map(json => readCollection[A](json, include.include).toList.asRight[DecodeFailure]) } } } trait JsonApiInstancesLowPrio { val mediaType: MediaType = new MediaType("application", "vnd.api+json") implicit def jsonapiJsObjectDecoder[F[_]: Effect]: EntityDecoder[F, JsObject] = EntityDecoder.decodeBy(mediaType) { msg: Message[F] => EitherT { msg.as[String].map(s => s.parseJson.asJsObject.asRight[DecodeFailure]) } } implicit def jsonapiDecoder[F[_]: Effect, A: JsonApiReader]: EntityDecoder[F, A] = EntityDecoder.decodeBy(mediaType) { msg: Message[F] => EitherT { msg.as[JsObject].map(json => readOne[A](json).asRight[DecodeFailure]) } } implicit def jsonapiListDecoder[F[_]: Effect, A: JsonApiReader]: EntityDecoder[F, List[A]] = EntityDecoder.decodeBy(mediaType) { msg: Message[F] => EitherT { msg.as[JsObject].map(json => readCollection[A](json).toList.asRight[DecodeFailure]) } } implicit def jsonapiEncoder[F[_], A: JsonApiWriter](implicit F: Applicative[F]): EntityEncoder[F, A] = EntityEncoder .stringEncoder(Charset.`UTF-8`) .contramap[A](entity => rawOne(entity).compactPrint) .withContentType(`Content-Type`(mediaType)) implicit def jsonapiListEncoder[F[_], A: JsonApiWriter](implicit F: Applicative[F]): EntityEncoder[F, List[A]] = EntityEncoder .stringEncoder(Charset.`UTF-8`) .contramap[List[A]](entities => rawCollection(entities).compactPrint) .withContentType(`Content-Type`(mediaType)) } object JsonApiInstances extends JsonApiInstances
Example 4
Source File: Lambda.scala From aws-lambda-scala with MIT License | 5 votes |
package io.github.mkotsur.aws.handler import java.io.{InputStream, OutputStream} import com.amazonaws.services.lambda.runtime.{Context, RequestStreamHandler} import io.circe.generic.auto._ import io.github.mkotsur.aws.codecs._ import io.github.mkotsur.aws.proxy.{ProxyRequest, ProxyResponse} import org.slf4j.LoggerFactory import cats.syntax.either.catsSyntaxEither import io.github.mkotsur.aws.handler.Lambda.HandleResult import scala.language.{higherKinds, postfixOps} import scala.util.{Failure, Success, Try} object Lambda extends AllCodec with ProxyRequestCodec { type Handle[I, O] = (I, Context) => HandleResult[O] type HandleResult[O] = Either[Throwable, O] type Proxy[I, O] = Lambda[ProxyRequest[I], ProxyResponse[O]] object Proxy { type Handle[I, O] = (ProxyRequest[I], Context) => HandleResult[O] type HandleResult[O] = Either[Throwable, ProxyResponse[O]] private type CanDecodeProxyRequest[A] = CanDecode[ProxyRequest[A]] private type CanEncodeProxyRequest[A] = CanEncode[ProxyResponse[A]] def instance[I: CanDecodeProxyRequest, O: CanEncodeProxyRequest]( doHandle: Proxy.Handle[I, O]): Lambda[ProxyRequest[I], ProxyResponse[O]] = new Lambda.Proxy[I, O] { override protected def handle(i: ProxyRequest[I], c: Context) = doHandle(i, c) } } def instance[I: CanDecode, O: CanEncode](doHandle: Handle[I, O]) = new Lambda[I, O] { override protected def handle(i: I, c: Context): Either[Throwable, O] = { super.handle(i, c) doHandle(i, c) } } type ReadStream[I] = InputStream => Either[Throwable, I] type ObjectHandler[I, O] = I => Either[Throwable, O] type WriteStream[O] = (OutputStream, Either[Throwable, O], Context) => Either[Throwable, Unit] private val logger = LoggerFactory.getLogger(getClass) } abstract class Lambda[I: CanDecode, O: CanEncode] extends RequestStreamHandler { final def handle(input: InputStream, output: OutputStream, context: Context): Unit = handleRequest(input, output, context) // This function will ultimately be used as the external handler final def handleRequest(input: InputStream, output: OutputStream, context: Context): Unit = { val read = implicitly[CanDecode[I]].readStream(input) val handled = read.flatMap { input => Try(handle(input, context)) match { case Success(v) => v case Failure(e) => Lambda.logger.error(s"Error while executing lambda handler: ${e.getMessage}", e) Left(e) } } val written = implicitly[CanEncode[O]].writeStream(output, handled, context) output.close() written.left.foreach(e => throw e) } }
Example 5
Source File: ProxyRequestCodec.scala From aws-lambda-scala with MIT License | 5 votes |
package io.github.mkotsur.aws.codecs import java.io.ByteArrayInputStream import cats.syntax.either.catsSyntaxEither import io.circe.generic.auto._ import io.github.mkotsur.aws.handler.CanDecode import io.github.mkotsur.aws.proxy.ProxyRequest import shapeless.Generic import scala.language.{higherKinds, postfixOps} private[aws] trait ProxyRequestCodec extends AllCodec with FutureCodec { def GenericProxyRequestOf[T] = shapeless.Generic[ProxyRequest[T]] implicit def canDecodeProxyRequest[T](implicit canDecode: CanDecode[T]) = CanDecode.instance[ProxyRequest[T]] { is => { def extractBody(s: ProxyRequest[String]) = s.body match { case Some(bodyString) => canDecode.readStream(new ByteArrayInputStream(bodyString.getBytes)).map(Option.apply) case None => Right(None) } def produceProxyResponse(decodedRequestString: ProxyRequest[String], bodyOption: Option[T]) = { val reqList = Generic[ProxyRequest[String]].to(decodedRequestString) Generic[ProxyRequest[T]].from((bodyOption :: reqList.reverse.tail).reverse) } for (decodedRequest$String <- CanDecode[ProxyRequest[String]].readStream(is); decodedBodyOption <- extractBody(decodedRequest$String)) yield produceProxyResponse(decodedRequest$String, decodedBodyOption) } } }
Example 6
Source File: TablePartitionName.scala From flamy with Apache License 2.0 | 5 votes |
package com.flaminem.flamy.model.names import com.flaminem.flamy.model.{PartitionColumn, PartitionKey} import com.flaminem.flamy.parsing.ParsingUtils import scala.language.{higherKinds, implicitConversions} class TablePartitionName(val fullName: String) extends ItemName { lazy val schemaName: SchemaName = SchemaName(tableFullName.split('.')(0)) lazy val tableName: TableName = TableName(tableFullName) private lazy val tableFullName: String = fullName.split('/')(0) lazy val partitionName: String = partColNames.mkString("/") lazy val partColNames: Seq[PartitionColumnName] = fullName.split('/').tail.map{PartitionColumnName} def partitionKeys: Seq[PartitionKey] = partColNames.map{_.toPartitionKey} def partitionColumns: Seq[PartitionColumn] = partColNames.map{_.toPartitionColumn} def isInSchema(schema: ItemName): Boolean = schema match { case s: SchemaName => s.equals(schemaName) case default => false } def isInTable(schema: ItemName): Boolean = schema match { case t: TableName => t.equals(tableName) case default => false } override def isInOrEqual(that: ItemName): Boolean = that match { case name: SchemaName => this.isInSchema(name) case name: TableName => this.isInTable(name) case name: TablePartitionName => name==this case _ => false } } object TablePartitionName { def apply(fullName: String): TablePartitionName = { parse(fullName).getOrElse{ throw new IllegalArgumentException(s"$fullName is not a correct TablePartitionName") } } def parse(s: String): Option[TablePartitionName] = { val t = ParsingUtils.t val tablePartitionRegex = s"\\A($t[.]$t)/(.*)\\z".r s match { case tablePartitionRegex(tableName, partitionName) => Some(new TablePartitionName(tableName.toLowerCase + "/" + partitionName)) case _ => None } } def unapply(tablePartitionName: TablePartitionName): Option[String] = Some(tablePartitionName.fullName) def apply(tableName: TableName, columnNames: PartitionColumnName*): TablePartitionName = { new TablePartitionName(tableName.fullName + "/" + columnNames.mkString("/")) } def apply(tableName: TableName, columnNames: String): TablePartitionName = { new TablePartitionName(tableName.fullName + "/" + columnNames) } implicit val order: Ordering[TablePartitionName] = new Ordering[TablePartitionName]{ override def compare(x: TablePartitionName, y: TablePartitionName): Int = x.fullName.compareTo(y.fullName) } }
Example 7
Source File: ItemName.scala From flamy with Apache License 2.0 | 5 votes |
package com.flaminem.flamy.model.names import com.flaminem.flamy.model.exceptions.FlamyException import org.rogach.scallop.ValueConverter import scala.collection.TraversableLike import scala.collection.generic.CanBuildFrom import scala.language.{higherKinds, implicitConversions} import scala.reflect.runtime.universe._ import scala.util.{Failure, Success, Try} def tryParse(s: String): Try[ItemName] = { Try{ SchemaName.parse(s) .orElse{ TableName.parse(s) } .orElse{ TablePartitionName.parse(s) } .getOrElse { throw new IllegalArgumentException("Wrong item name : " + s) } } } def tryParse(s: String, allowedTypes: Set[Class[_]]): Try[ItemName] = { tryParse(s).flatMap { case item if allowedTypes.contains(item.getClass) => Success(item) case item => Failure( new IllegalArgumentException( s"Item $item is a ${item.getClass.getSimpleName}, " + s"but only the following item types are allowed: ${allowedTypes.map{_.getSimpleName}.mkString("[", ", ", "]")}" ) ) } } implicit def fromStringTraversableLike[T[Z] <: TraversableLike[Z, T[Z]]] (l: T[String])(implicit bf: CanBuildFrom[T[String], ItemName, T[ItemName]]) : T[ItemName] = { l.map{tryParse(_).get} } private def fromArgs(args: Seq[String]): Either[String, Option[List[ItemName]]] = { val tries: Seq[Try[ItemName]] = args.map{tryParse} if(tries.forall{_.isSuccess}){ Right(Some(tries.map{_.get}.toList)) } else { val firstFailureIndex = tries.indexWhere(_.isFailure) Left(s"Could not parse the item name ${args(firstFailureIndex)}") } } implicit val scallopConverterList: ValueConverter[List[ItemName]] = { new ValueConverter[List[ItemName]] { override def parse(s: List[(String, List[String])]): Either[String, Option[List[ItemName]]] = { s match { case l if l.nonEmpty => fromArgs(l.flatMap{_._2}) case Nil => Right(None) } } override val tag: TypeTag[List[ItemName]] = typeTag[List[ItemName]] override val argType = org.rogach.scallop.ArgType.LIST } } }
Example 8
Source File: TraversableLikeExtension.scala From flamy with Apache License 2.0 | 5 votes |
package com.flaminem.flamy.utils.collection import scala.collection.TraversableLike import scala.collection.generic.CanBuildFrom import scala.collection.mutable.ListBuffer import scala.language.higherKinds def splitBy[B](fun: A => B)(implicit bf: CanBuildFrom[T[A], A, T[A]]): Iterable[(B, T[A])] = { if(t.isEmpty){ Nil } else { val buffer = new ListBuffer[(B, T[A])]() var groupBuilder = bf(t) var prevB: Option[B] = None t.foreach{ a => val b = Some(fun(a)) if(prevB != b){ if(prevB.isDefined){ buffer += prevB.get -> groupBuilder.result() } prevB = b groupBuilder = bf(t) } groupBuilder += a } buffer += prevB.get -> groupBuilder.result() buffer.result() } } }
Example 9
Source File: MonadError.scala From tapir with Apache License 2.0 | 5 votes |
package sttp.tapir.monad import scala.concurrent.{ExecutionContext, Future} import scala.language.higherKinds import scala.reflect.ClassTag import scala.util.{Failure, Success, Try} trait MonadError[F[_]] { def unit[T](t: T): F[T] def map[T, T2](fa: F[T])(f: T => T2): F[T2] def flatMap[T, T2](fa: F[T])(f: T => F[T2]): F[T2] def error[T](t: Throwable): F[T] protected def handleWrappedError[T](rt: F[T])(h: PartialFunction[Throwable, F[T]]): F[T] def handleError[T](rt: => F[T])(h: PartialFunction[Throwable, F[T]]): F[T] = { Try(rt) match { case Success(v) => handleWrappedError(v)(h) case Failure(e) if h.isDefinedAt(e) => h(e) case Failure(e) => error(e) } } } object MonadError { def recoverErrors[I, E, O, F[_]]( f: I => F[O] )(implicit eClassTag: ClassTag[E], eIsThrowable: E <:< Throwable): MonadError[F] => I => F[Either[E, O]] = { implicit monad => i => import sttp.tapir.monad.syntax._ monad.handleError(f(i).map(Right(_): Either[E, O])) { case e if eClassTag.runtimeClass.isInstance(e) => (Left(e.asInstanceOf[E]): Either[E, O]).unit } } } class FutureMonadError(implicit ec: ExecutionContext) extends MonadError[Future] { override def unit[T](t: T): Future[T] = Future.successful(t) override def map[T, T2](fa: Future[T])(f: (T) => T2): Future[T2] = fa.map(f) override def flatMap[T, T2](fa: Future[T])(f: (T) => Future[T2]): Future[T2] = fa.flatMap(f) override def error[T](t: Throwable): Future[T] = Future.failed(t) override protected def handleWrappedError[T](rt: Future[T])(h: PartialFunction[Throwable, Future[T]]): Future[T] = rt.recoverWith(h) }
Example 10
Source File: BasicScalaTypeConversions.scala From aloha with MIT License | 5 votes |
package com.eharmony.aloha.score.proto.conversions import scala.language.higherKinds import com.eharmony.aloha.score.Scores.Score trait BasicScalaTypeConversions [C[_] <: Option[_]] { def asBoolean(s: Score): C[Boolean] def asByte(s: Score): C[Byte] def asShort(s: Score): C[Short] def asInt(s: Score): C[Int] def asLong(s: Score): C[Long] def asFloat(s: Score): C[Float] def asDouble(s: Score): C[Double] def asString(s: Score): C[String] }
Example 11
Source File: ContainerReadableByString.scala From aloha with MIT License | 5 votes |
package com.eharmony.aloha.io import scala.language.higherKinds import org.apache.commons.io.IOUtils import java.lang.String import java.io.{ByteArrayOutputStream, Reader, InputStreamReader, InputStream} def fromReader[A](r: Reader): C[A] = { try { val baos = new ByteArrayOutputStream // Don't need to close. IOUtils.copy(r, baos, inputCharset) fromString[A](new String(baos.toByteArray)) } finally { IOUtils.closeQuietly(r) } } }
Example 12
Source File: ContainerReadable.scala From aloha with MIT License | 5 votes |
package com.eharmony.aloha.io import scala.language.higherKinds import java.io.{File, InputStream, Reader} import java.net.URL import org.apache.commons.{vfs => vfs1, vfs2} trait ContainerReadable[C[_]] { def fromString[A](s: String): C[A] def fromFile[A](f: File): C[A] def fromInputStream[A](is: InputStream): C[A] def fromUrl[A](u: URL): C[A] def fromReader[A](r: Reader): C[A] def fromVfs1[A](foVfs1: vfs1.FileObject): C[A] def fromVfs2[A](foVfs2: vfs2.FileObject): C[A] def fromResource[A](s: String): C[A] def fromClasspathResource[A](s: String): C[A] }
Example 13
Source File: RanCustomImpl.scala From scala_typeclassopedia with Creative Commons Attribution Share Alike 4.0 International | 5 votes |
package kan import cats.{Functor, Monad} import scala.language.higherKinds import org.scalatest.funspec.AnyFunSpec import org.scalatest.matchers.must.Matchers class RanCustomImpl extends AnyFunSpec with Matchers { describe("Right Kan extension implemented from Haskell definition") { def ranMonad[G[_]]: Monad[Ran3[G, G, ?]] = new Monad[Ran3[G, G, ?]] { override def map[A, B](fa: Ran3[G, G, A])(f: A => B): Ran3[G, G, B] = fa.map(f) override def flatMap[A, B](fa: Ran3[G, G, A])(f: A => Ran3[G, G, B]): Ran3[G, G, B] = flatten(map(fa)(f)) override def tailRecM[A, B](a: A)(f: A => Ran3[G, G, Either[A, B]]): Ran3[G, G, B] = ??? override def pure[A](x: A): Ran3[G, G, A] = new Ran3[G, G, A] { def runRan[C](f2: A => G[C]): G[C] = f2(x) } } } } }
Example 14
Source File: Find.scala From typed-schema with Apache License 2.0 | 5 votes |
package ru.tinkoff.tschema.common import shapeless._ import scala.language.higherKinds trait Find[F[_], L <: HList] { type Out def apply(l: L): F[Out] } sealed trait LowLevelFind { implicit def findTail[F[_], L <: HList, H](implicit tail: Find[F, L]): Find.Aux[F, H :: L, tail.Out] = new Find[F, H :: L] { type Out = tail.Out def apply(l: H :: L): F[tail.Out] = tail(l.tail) } } object Find extends LowLevelFind { def apply[F[_], L <: HList](implicit find: Find[F, L]): Aux[F, L, find.Out] = find type Aux[F[_], L <: HList, O] = Find[F, L] { type Out = O } implicit def findHead[F[_], L <: HList, X]: Aux[F, F[X] :: L, X] = new Find[F, F[X] :: L] { type Out = X def apply(l: F[X] :: L): F[X] = l.head } }
Example 15
Source File: circeDerivation.scala From typed-schema with Apache License 2.0 | 5 votes |
package ru.tinkoff.tschema.utils.json import io.circe._ import shapeless._ import shapeless.labelled.FieldType import scala.language.higherKinds object circeDerivation { @deprecated("use standard derivation", since = "0.3.0") def deriveObjEncoder[T](implicit enc: Lazy[DerivedCirceEncoder[T]]) = new Encoder.AsObject[T] { def encodeObject(a: T): JsonObject = enc.value.encodeObject(a) } } trait DerivedCirceEncoder[T] extends Encoder.AsObject[T] { def encodeObject(a: T): JsonObject } trait LowPriorityCirceEncoder { implicit def consEncoder[A, S <: Symbol, L <: HList](implicit head: Lazy[Encoder[A]], tail: DerivedCirceEncoder[L], witness: Witness.Aux[S] ) = new DerivedCirceEncoder[FieldType[S, A] :: L] { def encodeObject(obj: ::[FieldType[S, A], L]): JsonObject = tail.encodeObject(obj.tail).add(witness.value.name, head.value.apply(obj.head)) } } object DerivedCirceEncoder extends LowPriorityCirceEncoder { implicit val nilEncoder = new DerivedCirceEncoder[HNil] { override def encodeObject(a: HNil): JsonObject = JsonObject.empty } implicit val cnilEncoder = new DerivedCirceEncoder[CNil] { override def encodeObject(a: CNil): JsonObject = a.impossible } implicit def consNullableEncoder[A, S <: Symbol, L <: HList](implicit head: Lazy[Encoder[A]], tail: DerivedCirceEncoder[L], witness: Witness.Aux[S], nullable: Nullable[A] ) = new DerivedCirceEncoder[FieldType[S, A] :: L] { def encodeObject(obj: ::[FieldType[S, A], L]): JsonObject = { val tailEnc = tail.encodeObject(obj.tail) (obj.head: A) match { case nullable.zero => tailEnc case x => tailEnc.add(witness.value.name, head.value.apply(x)) } } } implicit def orEncoder[left, right <: Coproduct](implicit left: DerivedCirceEncoder[left], right: DerivedCirceEncoder[right] ) = new DerivedCirceEncoder[left :+: right] { def encodeObject(a: left :+: right): JsonObject = a match { case Inl(l: left @unchecked) => left.encodeObject(l) case Inr(r: right @unchecked) => right.encodeObject(r) } } implicit def deriveHListEncoder[T, L <: HList](implicit lgen: LabelledGeneric.Aux[T, L], enc: DerivedCirceEncoder[L] ) = new DerivedCirceEncoder[T] { def encodeObject(a: T): JsonObject = enc.encodeObject(lgen.to(a)) } implicit def deriveCoproductEncoder[T, C <: Coproduct](implicit gen: Generic.Aux[T, C], enc: DerivedCirceEncoder[C]) = new DerivedCirceEncoder[T] { def encodeObject(a: T): JsonObject = enc.encodeObject(gen.to(a)) } } case class Nullable[X](zero: X) extends AnyVal object Nullable { implicit def optionNullable[X] = Nullable[Option[X]](None) implicit def vectorNullable[X] = Nullable[Vector[X]](Vector.empty) implicit def mapNullable[K, V] = Nullable[Map[K, V]](Map.empty) }
Example 16
Source File: ParamMaker.scala From typed-schema with Apache License 2.0 | 5 votes |
package ru.tinkoff.tschema.macros import ru.tinkoff.tschema.macros.ParamMaker.Applyer import ru.tinkoff.tschema.typeDSL import ru.tinkoff.tschema.typeDSL.{Capture, DSLAtom, FormField, Header, QueryParam} import scala.language.{dynamics, higherKinds} import scala.language.experimental.macros import shapeless.Witness import scala.reflect.macros.whitebox class ParamMaker[T[_, _]] extends Dynamic { def params[A]: Applyer = macro ParamMakerMacro.paramsImpl[A, T[_, _]] } object ParamMaker { type Applyer = { def apply[A](x: => A): DSLAtom } def apply[T[_, _]]: ParamMaker[T] = new ParamMaker[T] object query extends ParamMaker[QueryParam] object path extends ParamMaker[Capture] object headers extends ParamMaker[Header] object form extends ParamMaker[FormField] } class ParamMakerMacro(val c: whitebox.Context) extends SymbolMacros { import c.universe._ val consTpe = typeOf[typeDSL.:>[_, _]].typeConstructor def paramsImpl[A: WeakTypeTag, T: WeakTypeTag] = { val const = weakTypeTag[T].tpe.typeConstructor val result = extractNamesTypes(weakTypeOf[A]).map { case (name, tpe) => appliedType(const, KeyName(name), tpe) } .reduce((a, b) => appliedType(consTpe, a, b)) q""" new { import ru.tinkoff.tschema.typeDSL.{:>} def apply[A](x: => A): :>[$result, A] = new :> }""" } def extractNamesTypes(ref: Type): List[(String, Type)] = ref match { case RefinedType(tpes, scope) => info(tpes) scope.collect { case m: MethodSymbol => info(m) m.name.decodedName.toString -> m.returnType }.toList case _ => List.empty } def info[A](mess: A) = c.info(c.enclosingPosition, mess.toString, force = false) }
Example 17
Source File: MonotonicDag.scala From crdt with Apache License 2.0 | 5 votes |
package com.machinomy.crdt.op import scala.language.higherKinds import scalax.collection.Graph import scalax.collection.GraphEdge._ import scalax.collection.GraphPredef._ case class MonotonicDag[V, E[X] <: DiEdgeLikeIn[X], G <: Graph[V, E]](graph: G)(implicit graphLike: DiGraphLike[V, E, G]) { def value = graph def add(e: E[V] with OuterEdge[V, E]): MonotonicDag.UpdateResult[V, E, G] = { val from = graphLike.fromVertex(graph, e) val to = graphLike.toVertex(value, e) val containsSource = graphLike.contains(value, from) val containsDestination = graphLike.contains(value, to) val effective = graphLike.addEdge(value, e) if (containsSource && containsDestination && graphLike.existsPath(effective, from, to)) { (MonotonicDag[V, E, G](effective), Some(MonotonicDag.AddEdge[V, E, G](e))) } else { (this, None) } } def add(v: V, left: V, right: V): MonotonicDag.UpdateResult[V, E, G] = { val absentV = !graphLike.contains(graph, v) val presentLeft = graphLike.contains(graph, left) val presentRight = graphLike.contains(graph, right) val existsPath = graphLike.existsPath(graph, left, right) if (absentV && presentLeft && presentRight && existsPath) { val g1 = graphLike.addVertex(graph, v) val g2 = graphLike.addEdge(g1, graphLike.buildEdge(left, v)) val g3 = graphLike.addEdge(g2, graphLike.buildEdge(v, right)) val next = MonotonicDag[V, E, G](g3) (next, Some(MonotonicDag.AddVertex[V, E, G](v, left, right))) } else { (this, None) } } } object MonotonicDag { type UpdateResult[V, E[X] <: DiEdgeLikeIn[X], G <: Graph[V, E]] = (MonotonicDag[V, E, G], Option[Update[V, E, G]]) sealed trait Update[V, E[X] <: DiEdgeLikeIn[X], G <: Graph[V, E]] case class AddEdge[V, E[X] <: DiEdgeLikeIn[X], G <: Graph[V, E]](e: E[V]) extends Update[V, E, G] case class AddVertex[V, E[X] <: DiEdgeLikeIn[X], G <: Graph[V, E]](v: V, left: V, right: V) extends Update[V, E, G] }
Example 18
Source File: monix.scala From sangria-monix with Apache License 2.0 | 5 votes |
package sangria.streaming import scala.language.higherKinds import _root_.monix.execution.Scheduler import _root_.monix.reactive._ import _root_.monix.eval.Task import cats.effect.ExitCase import scala.concurrent.Future object monix { class ObservableSubscriptionStream(implicit scheduler: Scheduler) extends SubscriptionStream[Observable] { def supported[T[_]](other: SubscriptionStream[T]) = other.isInstanceOf[ObservableSubscriptionStream] def map[A, B](source: Observable[A])(fn: A => B) = source.map(fn) def singleFuture[T](value: Future[T]) = Observable.fromFuture(value) def single[T](value: T) = Observable(value) def mapFuture[A, B](source: Observable[A])(fn: A => Future[B]) = source.mergeMap(a => Observable.fromFuture(fn(a))) def first[T](s: Observable[T]) = s.firstOrElseL(throw new IllegalStateException("Promise was not completed - observable haven't produced any elements.")).runToFuture def failed[T](e: Throwable) = Observable.raiseError(e) def onComplete[Ctx, Res](result: Observable[Res])(op: => Unit) = result.guaranteeCase { case ExitCase.Error(e) => Task(op) case _ => Task(op) } def flatMapFuture[Ctx, Res, T](future: Future[T])(resultFn: T => Observable[Res]) = Observable.fromFuture(future).mergeMap(resultFn) def merge[T](streams: Vector[Observable[T]]) = if (streams.nonEmpty) Observable(streams: _*).merge else throw new IllegalStateException("No streams produced!") def recover[T](stream: Observable[T])(fn: Throwable => T) = stream onErrorRecover {case e => fn(e)} } implicit def observableSubscriptionStream(implicit scheduler: Scheduler): SubscriptionStream[Observable] = new ObservableSubscriptionStream }
Example 19
Source File: Module.scala From scorch with BSD 2-Clause "Simplified" License | 5 votes |
package scorch.nn import com.typesafe.scalalogging.LazyLogging import scorch.autograd.Variable import scala.language.{higherKinds, implicitConversions} /* sealed trait Infer[F[_]] trait LowPriority { implicit def inferDefault[F[_]]: Infer[F] = new Infer[F] {} } object Infer extends LowPriority { type Id[A] = A implicit def inferId: Infer[Id] = new Infer[Id] {} } */ abstract class BaseModule(localParameters: Seq[Variable] = Nil) { // by default, obtain submodules through introspection lazy val subModules: Seq[BaseModule] = this.getClass.getDeclaredFields.flatMap { f => f setAccessible true f.get(this) match { case module: BaseModule => Some(module) case _ => None } } def parameters: Seq[Variable] = localParameters ++ subModules.flatMap(_.parameters) def gradients: Seq[Variable] = parameters.map(_.grad) def zeroGrad(): Unit = parameters.map(_.grad).foreach(g => g.data := 0) /* Pytorch way of solving distinction between training and test mode is by using a mutable variable. Perhaps there is a better way. */ var inTrainingMode: Boolean = false /* Sets the module in training mode. This has any effect only on modules such as Dropout or BatchNorm. */ def train(mode: Boolean = true): Unit = { this.inTrainingMode = mode subModules.foreach(_.train(mode)) } /* Sets the module in evaluation mode. This has any effect only on modules such as Dropout or BatchNorm. */ def eval(): Unit = train(false) } abstract class Module(localParameters: Seq[Variable] = Nil) extends BaseModule(localParameters) with LazyLogging { def forward(x: Variable): Variable def apply(x: Variable): Variable = forward(x) def par(parallelism: Int = Runtime.getRuntime.availableProcessors / 2): ParallelModule = { logger.info(s"parallelizing factor = $parallelism") ParallelModule(this, parallelism) } } abstract class SeqModule(localParameters: Seq[Variable] = Nil) extends BaseModule(localParameters) { def forward(xs: Seq[Variable]): Seq[Variable] def apply(xs: Seq[Variable]): Seq[Variable] = forward(xs) } /* abstract class Module[F[_]: Infer](localParameters: Seq[Variable] = Nil) extends BaseModule(localParameters) { def forward(x: F[Variable]): F[Variable] def apply(x: F[Variable]): F[Variable] = forward(x) } */
Example 20
Source File: SortableTables.scala From scalajs-bootstrap with MIT License | 5 votes |
package com.karasiq.bootstrap.table import scala.language.{higherKinds, postfixOps} import rx._ import com.karasiq.bootstrap.context.RenderingContext import com.karasiq.bootstrap.utils.Utils trait SortableTables extends TableCols { self: RenderingContext with PagedTables with Utils ⇒ import scalaTags.all._ type SortableTable[T] <: AbstractSortableTable[T] with BootstrapHtmlComponent val SortableTable: AbstractSortableTableFactory trait AbstractSortableTableFactory { def apply[T](items: Rx[Seq[T]], columns: Rx[Seq[TableCol[T, _]]], rowModifiers: T ⇒ Modifier = (_: T) ⇒ Bootstrap.noModifier, filterItem: (T, String) ⇒ Boolean = (i: T, f: String) ⇒ i.toString.contains(f)): SortableTable[T] } trait AbstractSortableTable[T] { def items: Rx[Seq[T]] def columns: Rx[GenTableCols[T]] def sortByColumn: Var[GenTableCol[T]] def reverseOrdering: Var[Boolean] def filter: Var[String] def filterItem(item: T, filter: String): Boolean def rowModifiers(item: T): Modifier def setOrdering(column: TableCol[T, _]): Unit = { if (sortByColumn.now == column) reverseOrdering() = !reverseOrdering.now else sortByColumn() = column } def pagedTable: PagedTable } }
Example 21
Source File: SortableTables.scala From scalajs-bootstrap with MIT License | 5 votes |
package com.karasiq.bootstrap4.table import scala.language.{higherKinds, postfixOps} import rx._ import com.karasiq.bootstrap.context.RenderingContext import com.karasiq.bootstrap4.utils.Utils trait SortableTables extends TableCols { self: RenderingContext with PagedTables with Utils ⇒ import scalaTags.all._ type SortableTable[T] <: AbstractSortableTable[T] with BootstrapHtmlComponent val SortableTable: AbstractSortableTableFactory trait AbstractSortableTableFactory { def apply[T](items: Rx[Seq[T]], columns: Rx[Seq[TableCol[T, _]]], rowModifiers: T ⇒ Modifier = (_: T) ⇒ Bootstrap.noModifier, filterItem: (T, String) ⇒ Boolean = (i: T, f: String) ⇒ i.toString.contains(f)): SortableTable[T] } trait AbstractSortableTable[T] { def items: Rx[Seq[T]] def columns: Rx[GenTableCols[T]] def sortByColumn: Var[GenTableCol[T]] def reverseOrdering: Var[Boolean] def filter: Var[String] def filterItem(item: T, filter: String): Boolean def rowModifiers(item: T): Modifier def setOrdering(column: TableCol[T, _]): Unit = { if (sortByColumn.now == column) reverseOrdering() = !reverseOrdering.now else sortByColumn() = column } def pagedTable: PagedTable } }
Example 22
Source File: SortingTools.scala From Clustering4Ever with Apache License 2.0 | 5 votes |
package org.clustering4ever.utils final def bucketSort(toSort: Array[Double], b: Int) = { val buckets = parallel.mutable.ParArray.fill(b)(mutable.ArrayBuffer.empty[Double]) val m = toSort.max @annotation.tailrec def go(i: Int) : Unit = { if(i < toSort.size) { buckets((toSort(i) / m * (b - 1)).toInt) += toSort(i) go(i + 1) } } go(0) buckets.flatMap(_.sorted) } }
Example 23
Source File: Statistics.scala From Clustering4Ever with Apache License 2.0 | 5 votes |
package org.clustering4ever.stats final def obtainMedianFollowingWeightedDistribution[V](distribution: Seq[(V, Double)]): V = { val p = scala.util.Random.nextDouble * distribution.foldLeft(0D)((agg, e) => agg + e._2) @annotation.tailrec def go(accum: Double, i: Int): Int = { if(accum < p) go(accum + distribution(i)._2, i + 1) else i } val cpt = go(0D, 0) if(cpt == 0) distribution.head._1 else distribution(cpt - 1)._1 } }
Example 24
Source File: K-Means.scala From Clustering4Ever with Apache License 2.0 | 5 votes |
package org.clustering4ever.clustering.kcenters.scala final def fit[D <: ContinuousDistance, GS[Y] <: GenSeq[Y]]( data: GS[Array[Double]], k: Int, metric: D, minShift: Double, maxIterations: Int ): KMeansModel[D] = { KMeans(k, metric, minShift, maxIterations, immutable.HashMap.empty[Int, ScalarVector]).fit(scalarToClusterizable(data)) } }
Example 25
Source File: KPPInitializer.scala From Clustering4Ever with Apache License 2.0 | 5 votes |
package org.clustering4ever.clustering.kcenters.scala final def kppInit[ O, V <: GVector[V], Cz[Y, Z <: GVector[Z]] <: Clusterizable[Y, Z, Cz], D <: Distance[V] ](data: GenSeq[Cz[O, V]], metric: D, k: Int): immutable.HashMap[Int, V] = { val centers = mutable.ArrayBuffer(data(Random.nextInt(data.size)).v) def obtainNearestCenter(v: V): V = centers.minBy(metric.d(_, v)) @annotation.tailrec def go(i: Int): Unit = { val preprocessed = data.map{ cz => val toPow2 = metric.d(cz.v, obtainNearestCenter(cz.v)) (cz.v, toPow2 * toPow2) } val phi = preprocessed.aggregate(0D)((agg, e) => agg + e._2, _ + _) val probabilities = preprocessed.map{ case (v, toPow2) => (v, toPow2 / phi) }.seq val shuffled = Random.shuffle(probabilities) centers += Stats.obtainMedianFollowingWeightedDistribution[V](shuffled) if(i < k - 2) go(i + 1) } go(0) immutable.HashMap(centers.zipWithIndex.map{ case (center, clusterID) => (clusterID, center) }:_*) } }
Example 26
Source File: K-Modes.scala From Clustering4Ever with Apache License 2.0 | 5 votes |
package org.clustering4ever.clustering.kcenters.scala final def fit[D <: BinaryDistance, GS[Y] <: GenSeq[Y]]( data: GS[Array[Int]], k: Int, metric: D, maxIterations: Int, minShift: Double ): KModesModel[D] = { KModes(k, metric, minShift, maxIterations).fit(binaryToClusterizable(data)) } }
Example 27
Source File: UtilSpark.scala From Clustering4Ever with Apache License 2.0 | 5 votes |
package org.clustering4ever.sparktools import scala.language.higherKinds import org.apache.spark.rdd.RDD import org.apache.spark.HashPartitioner import scala.reflect.runtime.universe.TypeTag import scala.util.Random import scala.reflect.ClassTag import scala.collection.{GenSeq, mutable} import org.clustering4ever.preprocessing.Preprocessable import org.clustering4ever.hashing.HashingScalar import org.clustering4ever.vectors.{GVector, ScalarVector} object UtilSpark { type IndexPartition = Int type HasConverged = Boolean type IsOriginalDot = Boolean final def generateDataLocalityOnHashsedDS[ O, Pz[B, C <: GVector[C]] <: Preprocessable[B, C, Pz] ]( rddToPartitioned: RDD[Pz[O, ScalarVector]], nbblocs1: Int, nbBucketRange: Int ): RDD[(IndexPartition, (Pz[O, ScalarVector], IsOriginalDot, HasConverged))] = { val isOriginalPoint = true val hasConverged = true val bucketRange = 1 to nbBucketRange val lshRDD = rddToPartitioned.map((_, isOriginalPoint, !hasConverged)) val localityPerPartitionRDD = lshRDD.mapPartitionsWithIndex{ (idx, it) => val ar = it.toList def rightNeighbourhood = ar.flatMap{ case (cz, _, _) => bucketRange.collect{ case i if(idx + i < nbblocs1) => (idx + i, (cz, !isOriginalPoint, !hasConverged)) } } def leftNeighbourhood = ar.flatMap{ case (cz, _, _) => bucketRange.collect{ case i if(idx - i >= 0) => (idx - i, (cz, !isOriginalPoint, !hasConverged)) } } val composing = if(idx == 0) ar.map((idx, _)) ::: rightNeighbourhood else if(idx == nbblocs1 - 1) ar.map((idx, _)) ::: leftNeighbourhood else ar.map((idx, _)) ::: leftNeighbourhood ::: rightNeighbourhood composing.toIterator }.partitionBy(new HashPartitioner(nbblocs1)) localityPerPartitionRDD } final def generateDataLocalityLD[ O, Pz[B, C <: GVector[C]] <: Preprocessable[B, C, Pz], Hasher <: HashingScalar ]( rddToPartitioned: RDD[Pz[O, ScalarVector]], hashing: Hasher, nbblocs1: Int, nbBucketRange: Int ): RDD[(IndexPartition, (Pz[O, ScalarVector], IsOriginalDot, HasConverged))] = { val hashedRDD = rddToPartitioned.sortBy( cz => hashing.hf(cz.v) , ascending = true, nbblocs1 ) generateDataLocalityOnHashsedDS(hashedRDD, nbblocs1, nbBucketRange) } }
Example 28
Source File: K-Centers.scala From Clustering4Ever with Apache License 2.0 | 5 votes |
package org.clustering4ever.clustering.kcenters.dataset @annotation.tailrec def go(cpt: Int, haveAllCentersConverged: Boolean, centers: List[(Int, V)]): List[(Int, V)] = { val preUpdatedCenters = data.groupByKey( cz => obtainNearestCenterID(cz.v, centers, metric) )(encoderInt) .mapGroups(computeCenters)(encoder) .collect .sortBy(_._1) .toList val alignedOldCenters = preUpdatedCenters.map{ case (oldClusterID, _) => centers(oldClusterID) } val updatedCenters = preUpdatedCenters.zipWithIndex.map{ case ((oldClusterID, center), newClusterID) => (newClusterID, center) } val shiftingEnough = areCentersNotMovingEnough(updatedCenters, alignedOldCenters, minShift, metric) if(cpt < maxIterations && !shiftingEnough) { go(cpt + 1, shiftingEnough, updatedCenters) } else { updatedCenters } } immutable.HashMap(go(0, false, centers):_*) } }
Example 29
Source File: K-Means.scala From Clustering4Ever with Apache License 2.0 | 5 votes |
package org.clustering4ever.clustering.kcenters.rdd final def fit[D <: ContinuousDistance]( data: RDD[Array[Double]], k: Int, metric: D, minShift: Double, maxIterations: Int, persistanceLVL: StorageLevel ): KMeansModel[D] = { KMeans(k, metric, minShift, maxIterations, persistanceLVL).fit(scalarDataWithIDToClusterizable(data.zipWithIndex)) } }
Example 30
Source File: K-Modes.scala From Clustering4Ever with Apache License 2.0 | 5 votes |
package org.clustering4ever.clustering.kcenters.rdd final def fit[D <: BinaryDistance]( data: RDD[Array[Int]], k: Int, metric: D, minShift: Double, maxIterations: Int, persistanceLVL: StorageLevel ): KModesModel[D] = { KModes(k, metric, minShift, maxIterations, persistanceLVL).fit(binaryDataWithIDToClusterizable(data.zipWithIndex)) } }
Example 31
Source File: DistributedRoughSet.scala From Clustering4Ever with Apache License 2.0 | 5 votes |
package org.clustering4ever.spark.preprocessing.rst final def runHeuristic[O, T : ClassTag, V[A] <: GSimpleVector[A, V[A]], Sz[B, C <: GVector[C]] <: Supervizable[B, C, Sz]](data: RDD[Sz[O, V[T]]], columnsOfFeats: Seq[Seq[Int]]): mutable.Buffer[Int] = { val nbColumns = columnsOfFeats.size val dataBC = sc.broadcast(data.collect.par) sc.parallelize(0 until 8888, nbColumns).mapPartitionsWithIndex{ (idxp, _) => val dataPerFeat = dataBC.value.map(_.obtainOneBucket(idxp)) val originalFeatures = columnsOfFeats(idxp) val originalFeatIdByTmpFeatId = originalFeatures.zipWithIndex.map(_.swap).toMap val allReductSet = roughSet(dataPerFeat) allReductSet(Random.nextInt(allReductSet.size)).map(originalFeatIdByTmpFeatId).toIterator } .collect .toBuffer } }
Example 32
Source File: Assertions.scala From daml with Apache License 2.0 | 5 votes |
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved. // SPDX-License-Identifier: Apache-2.0 package com.daml.ledger.api.testtool.infrastructure import ai.x.diff.DiffShow import com.daml.grpc.{GrpcException, GrpcStatus} import java.util.regex.Pattern import io.grpc.Status import scala.language.higherKinds import scala.util.control.NonFatal object Assertions extends DiffExtensions { def fail(message: String): Nothing = throw new AssertionError(message) def fail(message: String, cause: Throwable): Nothing = throw new AssertionError(message, cause) def assertLength[A, F[_] <: Seq[_]](context: String, length: Int, as: F[A]): F[A] = { assert(as.length == length, s"$context: expected $length item(s), got ${as.length}") as } def assertSingleton[A](context: String, as: Seq[A]): A = assertLength(context, 1, as).head def assertEquals[T: DiffShow](context: String, actual: T, expected: T): Unit = { val diff = DiffShow.diff(actual, expected) if (!diff.isIdentical) throw AssertionErrorWithPreformattedMessage( diff.string, s"$context: two objects are supposed to be equal but they are not", ) } def assertGrpcError(t: Throwable, expectedCode: Status.Code, pattern: String): Unit = { assertGrpcError( t, expectedCode, if (pattern.isEmpty) None else Some(Pattern.compile(Pattern.quote(pattern)))) } }
Example 33
Source File: CustomScoptReaders.scala From daml with Apache License 2.0 | 5 votes |
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved. // SPDX-License-Identifier: Apache-2.0 package com.daml.extractor.config import com.daml.lf.data.Ref.Party import scalaz.OneAnd import scopt.Read import scopt.Read.reads import scala.language.higherKinds import scala.collection.breakOut import scala.collection.generic.CanBuildFrom private[extractor] object CustomScoptReaders { implicit val partyRead: Read[Party] = reads { s => Party fromString s fold (e => throw new IllegalArgumentException(e), identity) } implicit val templateConfigRead: Read[TemplateConfig] = reads { s => s.split(':') match { case Array(moduleName, entityName) => TemplateConfig(moduleName, entityName) case _ => throw new IllegalArgumentException( s"Expected TemplateConfig string: '<moduleName>:<entityName>', got: '$s'") } } implicit def nonEmptySeqRead[F[_], A]( implicit ev: Read[A], target: CanBuildFrom[Nothing, A, F[A]]): Read[OneAnd[F, A]] = reads { s => val Array(hd, tl @ _*) = s split Read.sep OneAnd(ev reads hd, tl.map(ev.reads)(breakOut)) } }
Example 34
Source File: InsertDeleteStep.scala From daml with Apache License 2.0 | 5 votes |
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved. // SPDX-License-Identifier: Apache-2.0 package com.daml.http package util import com.daml.http.dbbackend.Queries.DBContract import com.daml.ledger.api.v1.{event => evv1} import scalaz.{Monoid, \/, \/-} import scalaz.syntax.tag._ import scala.collection.generic.CanBuildFrom import scala.runtime.AbstractFunction1 import scala.language.higherKinds private[http] final case class InsertDeleteStep[+D, +C]( inserts: InsertDeleteStep.Inserts[C], deletes: Map[String, D]) { import InsertDeleteStep._ def append[DD >: D, CC >: C: Cid](o: InsertDeleteStep[DD, CC]): InsertDeleteStep[DD, CC] = InsertDeleteStep( appendForgettingDeletes(inserts, o), deletes ++ o.deletes, ) def nonEmpty: Boolean = inserts.nonEmpty || deletes.nonEmpty def leftMap[DD](f: D => DD): InsertDeleteStep[DD, C] = copy(deletes = deletes transform ((_, d) => f(d))) def partitionBimap[LD, DD, LC, CC, LDS](f: D => (LD \/ DD), g: C => (LC \/ CC))( implicit LDS: CanBuildFrom[Map[String, D], LD, LDS], ): (LDS, Inserts[LC], InsertDeleteStep[DD, CC]) = { import Collections._ import scalaz.std.tuple._, scalaz.syntax.traverse._ val (lcs, ins) = inserts partitionMap g val (lds, del) = deletes partitionMap (_ traverse f) (lds, lcs, copy(inserts = ins, deletes = del)) } } private[http] object InsertDeleteStep extends WithLAV1[InsertDeleteStep] { type Inserts[+C] = Vector[C] val Inserts: Vector.type = Vector val Empty: InsertDeleteStep[Nothing, Nothing] = apply(Vector.empty, Map.empty) abstract class Cid[-C] extends (C AbstractFunction1 String) @SuppressWarnings(Array("org.wartremover.warts.Any")) object Cid { implicit val ofDBC: Cid[DBContract[Any, Any, Any, Any]] = _.contractId implicit val ofAC: Cid[domain.ActiveContract[Any]] = _.contractId.unwrap implicit def ofFst[L](implicit L: Cid[L]): Cid[(L, Any)] = la => L(la._1) // ofFst and ofSnd should *not* both be defined, being incoherent together } // we always use the Last semigroup for D implicit def `IDS monoid`[D, C: Cid]: Monoid[InsertDeleteStep[D, C]] = Monoid instance (_ append _, Empty) def appendForgettingDeletes[D, C](leftInserts: Inserts[C], right: InsertDeleteStep[Any, C])( implicit cid: Cid[C], ): Inserts[C] = (if (right.deletes.isEmpty) leftInserts else leftInserts.filter(c => !right.deletes.isDefinedAt(cid(c)))) ++ right.inserts } private[http] trait WithLAV1[F[_, _]] { type LAV1 = F[evv1.ArchivedEvent, evv1.CreatedEvent] }
Example 35
Source File: FutureUtil.scala From daml with Apache License 2.0 | 5 votes |
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved. // SPDX-License-Identifier: Apache-2.0 package com.daml.http.util import scalaz.syntax.show._ import scalaz.{-\/, Applicative, EitherT, Functor, Show, \/, \/-} import scala.concurrent.{ExecutionContext, Future} import scala.language.higherKinds import scala.util.Try object FutureUtil { def toFuture[A](o: Option[A]): Future[A] = o.fold(Future.failed[A](new IllegalStateException(s"Empty option: $o")))(a => Future.successful(a)) def toFuture[A](a: Try[A]): Future[A] = a.fold(e => Future.failed(e), a => Future.successful(a)) def toFuture[A: Show, B](a: A \/ B): Future[B] = a.fold(e => Future.failed(new IllegalStateException(e.shows)), a => Future.successful(a)) def toFuture[A](a: Throwable \/ A): Future[A] = a.fold(e => Future.failed(new IllegalStateException(e)), a => Future.successful(a)) def liftET[E]: LiftET[E] = new LiftET(0) final class LiftET[E](private val ignore: Int) extends AnyVal { def apply[F[_]: Functor, A](fa: F[A]): EitherT[F, E, A] = EitherT.rightT(fa) } def eitherT[A, B](fa: Future[A \/ B]): EitherT[Future, A, B] = EitherT.eitherT[Future, A, B](fa) def either[A, B](d: A \/ B)(implicit ev: Applicative[Future]): EitherT[Future, A, B] = EitherT.either[Future, A, B](d) def rightT[A, B](fa: Future[B])(implicit ev: Functor[Future]): EitherT[Future, A, B] = EitherT.rightT(fa) def leftT[A, B](fa: Future[A])(implicit ev: Functor[Future]): EitherT[Future, A, B] = EitherT.leftT(fa) def stripLeft[A: Show, B](fa: Future[A \/ B])(implicit ec: ExecutionContext): Future[B] = fa.flatMap { case -\/(e) => Future.failed(new IllegalStateException(e.shows)) case \/-(a) => Future.successful(a) } }
Example 36
Source File: NavigatorModelAliases.scala From daml with Apache License 2.0 | 5 votes |
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved. // SPDX-License-Identifier: Apache-2.0 package com.daml.lf package value.json import data.{Ref => DamlLfRef} import value.{Value => V} type DamlLfEnum = iface.Enum val DamlLfEnum = iface.Enum def damlLfInstantiate(typeCon: DamlLfTypeCon, defn: DamlLfDefDataType): DamlLfDataType = if (defn.typeVars.length != typeCon.typArgs.length) { throw new RuntimeException( s"Mismatching type vars and applied types, expected ${defn.typeVars} but got ${typeCon.typArgs} types") } else { if (defn.typeVars.isEmpty) { // optimization defn.dataType } else { val paramsMap = Map(defn.typeVars.zip(typeCon.typArgs): _*) def mapTypeVars(typ: DamlLfType, f: DamlLfTypeVar => DamlLfType): DamlLfType = typ match { case t @ DamlLfTypeVar(_) => f(t) case t @ DamlLfTypeCon(_, _) => DamlLfTypeCon(t.name, t.typArgs.map(mapTypeVars(_, f))) case t @ DamlLfTypePrim(_, _) => DamlLfTypePrim(t.typ, t.typArgs.map(mapTypeVars(_, f))) case t @ DamlLfTypeNumeric(_) => t } val withTyp: iface.Type => iface.Type = { typ => mapTypeVars(typ, v => paramsMap.getOrElse(v.name, v)) } defn.dataType.bimap(withTyp, withTyp) } } import scala.language.higherKinds type OfCid[V[_]] = V[Cid] type ApiValue = OfCid[V] type ApiRecordField = (Option[DamlLfRef.Name], ApiValue) type ApiRecord = OfCid[V.ValueRecord] type ApiVariant = OfCid[V.ValueVariant] type ApiList = OfCid[V.ValueList] type ApiOptional = OfCid[V.ValueOptional] type ApiMap = OfCid[V.ValueTextMap] type ApiGenMap = OfCid[V.ValueGenMap] type ApiImpossible = OfCid[V.ValueStruct] } object NavigatorModelAliases extends NavigatorModelAliases[String]
Example 37
Source File: domain.scala From daml with Apache License 2.0 | 5 votes |
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved. // SPDX-License-Identifier: Apache-2.0 package com.daml.jwt import scalaz.syntax.applicative._ import scalaz.{Applicative, Traverse} import scala.language.higherKinds package object domain { final case class KeyPair[A](publicKey: A, privateKey: A) final case class Jwt(value: String) final case class DecodedJwt[A](header: A, payload: A) object KeyPair { implicit val traverseInstance: Traverse[KeyPair] = new Traverse[KeyPair] { override def traverseImpl[G[_]: Applicative, A, B](fa: KeyPair[A])( f: A => G[B]): G[KeyPair[B]] = { ^(f(fa.publicKey), f(fa.privateKey))(KeyPair(_, _)) } } } object DecodedJwt { implicit val traverseInstance: Traverse[DecodedJwt] = new Traverse[DecodedJwt] { override def traverseImpl[G[_]: Applicative, A, B](fa: DecodedJwt[A])( f: A => G[B]): G[DecodedJwt[B]] = { ^(f(fa.header), f(fa.payload))((h, p) => DecodedJwt(header = h, payload = p)) } } } }
Example 38
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved. // SPDX-License-Identifier: Apache-2.0 package com.daml.lf package archive import scalaz.{Applicative, Equal, Traverse} import scalaz.syntax.equal._ import scalaz.std.list._ import scala.language.higherKinds final case class Dar[A](main: A, dependencies: List[A]) { lazy val all: List[A] = main :: dependencies } object Dar { implicit val darTraverse: Traverse[Dar] = new Traverse[Dar] { override def map[A, B](fa: Dar[A])(f: A => B): Dar[B] = Dar[B](main = f(fa.main), dependencies = fa.dependencies.map(f)) override def traverseImpl[G[_]: Applicative, A, B](fa: Dar[A])(f: A => G[B]): G[Dar[B]] = { import scalaz.syntax.apply._ import scalaz.syntax.traverse._ import scalaz.std.list._ val gb: G[B] = f(fa.main) val gbs: G[List[B]] = fa.dependencies.traverse(f) ^(gb, gbs)((b, bs) => Dar(b, bs)) } } implicit def darEqual[A: Equal]: Equal[Dar[A]] = new Equal[Dar[A]] { override def equal(a1: Dar[A], a2: Dar[A]): Boolean = a1.main === a2.main && a1.dependencies === a2.dependencies } }
Example 39
Source File: MapKOps.scala From daml with Apache License 2.0 | 5 votes |
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved. // SPDX-License-Identifier: Apache-2.0 package com.daml.lf.data import scala.language.higherKinds import scala.collection.GenTraversableOnce import scala.collection.immutable.{Map, MapLike} trait MapKOps[K, +V, +This[+TV] <: Map[K, TV] with MapKOps[K, TV, This]] extends MapLike[K, V, This[V]] { this: This[V] => override def updated[V1 >: V](key: K, value: V1): This[V1] = this + ((key, value)) override def +[V1 >: V](kv: (K, V1)): This[V1] override def +[V1 >: V](elem1: (K, V1), elem2: (K, V1), elems: (K, V1)*): This[V1] = this + elem1 + elem2 ++ elems override def ++[V1 >: V](xs: GenTraversableOnce[(K, V1)]): This[V1] = xs.seq.foldLeft(this: This[V1])(_ + _) }
Example 40
Source File: SortedLookupList.scala From daml with Apache License 2.0 | 5 votes |
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved. // SPDX-License-Identifier: Apache-2.0 package com.daml.lf.data import ScalazEqual.{equalBy, orderBy} import scala.language.higherKinds import scalaz.{Applicative, Equal, Order, Traverse} import scalaz.std.tuple._ import scalaz.std.string._ import scalaz.syntax.traverse._ import scala.collection.immutable.HashMap // Note that keys are ordered using Utf8 ordering final class SortedLookupList[+X] private (entries: ImmArray[(String, X)]) extends Equals { def mapValue[Y](f: X => Y) = new SortedLookupList(entries.map { case (k, v) => k -> f(v) }) def toImmArray: ImmArray[(String, X)] = entries def keys: ImmArray[String] = entries.map(_._1) def values: ImmArray[X] = entries.map(_._2) def iterator: Iterator[(String, X)] = entries.iterator def toHashMap: HashMap[String, X] = HashMap(entries.toSeq: _*) def foreach(f: ((String, X)) => Unit): Unit = entries.foreach(f) override def canEqual(that: Any): Boolean = that.isInstanceOf[SortedLookupList[_]] override def equals(obj: Any): Boolean = { obj match { case other: SortedLookupList[X] if other canEqual this => other.toImmArray == entries case _ => false } } override def hashCode(): Int = entries.hashCode() override def toString: String = s"SortedLookupList(${entries.map { case (k, v) => k -> v }.toSeq.mkString(",")})" } object SortedLookupList extends SortedLookupListInstances { def fromImmArray[X](entries: ImmArray[(String, X)]): Either[String, SortedLookupList[X]] = { entries.toSeq .groupBy(_._1) .collectFirst { case (k, l) if l.size > 1 => s"key $k duplicated when trying to build map" } .toLeft(new SortedLookupList(entries.toSeq.sortBy(_._1)(Utf8.Ordering).toImmArray)) } def fromSortedImmArray[X](entries: ImmArray[(String, X)]): Either[String, SortedLookupList[X]] = { entries .map(_._1) .toSeq .sliding(2) .collectFirst { case Seq(k1, k2) if Utf8.Ordering.gteq(k1, k2) => s"the list $entries is not sorted by key" } .toLeft(new SortedLookupList(entries)) } def apply[X](entries: Map[String, X]): SortedLookupList[X] = new SortedLookupList(ImmArray(entries.toSeq.sortBy(_._1))) def empty[X]: SortedLookupList[X] = new SortedLookupList(ImmArray.empty) implicit def `SLL Order instance`[X: Order]: Order[SortedLookupList[X]] = orderBy(_.toImmArray, true) implicit val `SLL covariant instance`: Traverse[SortedLookupList] = new Traverse[SortedLookupList] { override def traverseImpl[G[_]: Applicative, A, B](fa: SortedLookupList[A])( f: A => G[B]): G[SortedLookupList[B]] = fa.toImmArray traverse (_ traverse f) map (new SortedLookupList(_)) } } sealed abstract class SortedLookupListInstances { implicit def `SLL Equal instance`[X: Equal]: Equal[SortedLookupList[X]] = equalBy(_.toImmArray, true) }
Example 41
Source File: InvariantApply.scala From daml with Apache License 2.0 | 5 votes |
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved. // SPDX-License-Identifier: Apache-2.0 package com.daml.ledger.client.binding.encoding import scala.language.higherKinds import scalaz.{-\/, Apply, Divide, InvariantFunctor, \/, \/-} def applyApplicative: InvariantApply[Lambda[a => F[a] \/ a]] = new InvariantApply.OneOr()(this) } object InvariantApply { def fromApply[F[_]](implicit F: Apply[F]): InvariantApply[F] = new InvariantApply[F] { override def xmap[A, B](fa: F[A], f: A => B, g: B => A) = F.xmap(fa, f, g) override def xmapN[A, B, Z](fa: F[A], fb: F[B])(f: (A, B) => Z)(g: Z => (A, B)) = F.apply2(fa, fb)(f) } def fromDivide[F[_]](implicit F: Divide[F]): InvariantApply[F] = new InvariantApply[F] { override def xmap[A, B](fa: F[A], f: A => B, g: B => A) = F.xmap(fa, f, g) override def xmapN[A, B, Z](fa: F[A], fb: F[B])(f: (A, B) => Z)(g: Z => (A, B)) = F.divide(fa, fb)(g) } private final class Product[F[_], G[_]](implicit F: InvariantApply[F], G: InvariantApply[G]) extends InvariantApply[Lambda[a => (F[a], G[a])]] { type Pair[A] = (F[A], G[A]) override def xmap[A, B](fa: Pair[A], f: A => B, g: B => A) = (F.xmap(fa._1, f, g), G.xmap(fa._2, f, g)) override def xmapN[A, B, Z](fa: Pair[A], fb: Pair[B])(f: (A, B) => Z)(g: Z => (A, B)) = (F.xmapN(fa._1, fb._1)(f)(g), G.xmapN(fa._2, fb._2)(f)(g)) } private final class OneOr[F[_]](implicit F: InvariantApply[F]) extends InvariantApply[Lambda[a => F[a] \/ a]] { override def xmap[A, B](fa: F[A] \/ A, f: A => B, g: B => A) = fa bimap (F.xmap(_, f, g), f) override def xmapN[A, B, Z](faa: F[A] \/ A, fbb: F[B] \/ B)(f: (A, B) => Z)(g: Z => (A, B)) = (faa, fbb) match { case (-\/(fa), -\/(fb)) => -\/(F.xmapN(fa, fb)(f)(g)) case (-\/(fa), \/-(b)) => -\/(F.xmapN(fa)(f(_, b))(g(_)._1)) case (\/-(a), -\/(fb)) => -\/(F.xmapN(fb)(f(a, _))(g(_)._2)) case (\/-(a), \/-(b)) => \/-(f(a, b)) } } }
Example 42
Source File: LfEncodable.scala From daml with Apache License 2.0 | 5 votes |
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved. // SPDX-License-Identifier: Apache-2.0 package com.daml.ledger.client package binding package encoding import scala.language.higherKinds import binding.{Primitive => P} @annotation.implicitNotFound(msg = "Cannot find LfEncodable type class for ${A}") abstract class LfEncodable[A] { def encoding(lte: LfTypeEncoding): lte.Out[A] } object LfEncodable extends ValuePrimitiveEncoding[LfEncodable] { @inline def encoding[A](lte: LfTypeEncoding)(implicit le: LfEncodable[A]): lte.Out[A] = le.encoding(lte) override implicit val valueInt64: LfEncodable[P.Int64] = new LfEncodable[P.Int64] { override def encoding(lte: LfTypeEncoding): lte.Out[P.Int64] = lte.primitive.valueInt64 } override implicit val valueNumeric: LfEncodable[P.Numeric] = new LfEncodable[P.Numeric] { override def encoding(lte: LfTypeEncoding): lte.Out[P.Numeric] = lte.primitive.valueNumeric } override implicit val valueParty: LfEncodable[P.Party] = new LfEncodable[P.Party] { override def encoding(lte: LfTypeEncoding): lte.Out[P.Party] = lte.primitive.valueParty } override implicit val valueText: LfEncodable[P.Text] = new LfEncodable[P.Text] { override def encoding(lte: LfTypeEncoding): lte.Out[P.Text] = lte.primitive.valueText } override implicit val valueDate: LfEncodable[P.Date] = new LfEncodable[P.Date] { override def encoding(lte: LfTypeEncoding): lte.Out[P.Date] = lte.primitive.valueDate } override implicit val valueTimestamp: LfEncodable[P.Timestamp] = new LfEncodable[P.Timestamp] { override def encoding(lte: LfTypeEncoding): lte.Out[P.Timestamp] = lte.primitive.valueTimestamp } override implicit val valueUnit: LfEncodable[P.Unit] = new LfEncodable[P.Unit] { override def encoding(lte: LfTypeEncoding): lte.Out[P.Unit] = lte.primitive.valueUnit } override implicit val valueBool: LfEncodable[P.Bool] = new LfEncodable[P.Bool] { override def encoding(lte: LfTypeEncoding): lte.Out[P.Bool] = lte.primitive.valueBool } override implicit def valueList[A: LfEncodable]: LfEncodable[P.List[A]] = new LfEncodable[P.List[A]] { override def encoding(lte: LfTypeEncoding): lte.Out[P.List[A]] = lte.primitive.valueList(LfEncodable.encoding[A](lte)) } override implicit def valueContractId[A]: LfEncodable[P.ContractId[A]] = new LfEncodable[P.ContractId[A]] { override def encoding(lte: LfTypeEncoding): lte.Out[P.ContractId[A]] = lte.primitive.valueContractId } override implicit def valueOptional[A: LfEncodable]: LfEncodable[P.Optional[A]] = new LfEncodable[P.Optional[A]] { override def encoding(lte: LfTypeEncoding): lte.Out[P.Optional[A]] = lte.primitive.valueOptional(LfEncodable.encoding[A](lte)) } override implicit def valueTextMap[A: LfEncodable]: LfEncodable[P.TextMap[A]] = new LfEncodable[P.TextMap[A]] { override def encoding(lte: LfTypeEncoding): lte.Out[P.TextMap[A]] = lte.primitive.valueTextMap(LfEncodable.encoding[A](lte)) } override implicit def valueGenMap[K: LfEncodable, V: LfEncodable]: LfEncodable[P.GenMap[K, V]] = new LfEncodable[P.GenMap[K, V]] { override def encoding(lte: LfTypeEncoding): lte.Out[P.GenMap[K, V]] = lte.primitive.valueGenMap(LfEncodable.encoding[K](lte), LfEncodable.encoding[V](lte)) } trait ViaFields[T] { type view[C[_]] <: RecordView[C, view] def fieldEncoding(lte: LfTypeEncoding): view[lte.Field] def encoding(lte: LfTypeEncoding)(view: view[lte.Field]): lte.Out[T] } }
Example 43
Source File: TemplateCompanion.scala From daml with Apache License 2.0 | 5 votes |
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved. // SPDX-License-Identifier: Apache-2.0 package com.daml.ledger.client.binding import scala.language.higherKinds import com.daml.ledger.api.refinements.ApiTypes.{Choice, TemplateId} import com.daml.ledger.api.v1.{event => rpcevent, value => rpcvalue} import rpcvalue.Value.{Sum => VSum} import encoding.{ExerciseOn, LfEncodable, LfTypeEncoding, RecordView} import scalaz.Liskov import Liskov.<~< private[binding] final def decoderEntry : (Primitive.TemplateId[T], rpcevent.CreatedEvent => Option[Template[T]]) = { type K[+A] = (Primitive.TemplateId[T], rpcevent.CreatedEvent => Option[A]) Liskov.co[K, T, Template[T]](describesTemplate)( (id, _.createArguments flatMap fromNamedArguments)) } protected final def ` exercise`[ExOn, Out]( receiver: ExOn, choiceId: String, arguments: Option[rpcvalue.Value])( implicit exon: ExerciseOn[ExOn, T]): Primitive.Update[Out] = Primitive.exercise(this, receiver, choiceId, arguments getOrElse Value.encode(())) protected final def ` arguments`(elems: (String, rpcvalue.Value)*): rpcvalue.Record = Primitive.arguments(` dataTypeId`, elems) } object TemplateCompanion { abstract class Empty[T](implicit isTemplate: T <~< Template[T]) extends TemplateCompanion[T] { protected def onlyInstance: T type view[C[_]] = RecordView.Empty[C] override def toNamedArguments(associatedType: T) = ` arguments`() override def fromNamedArguments(namedArguments: rpcvalue.Record): Option[T] = Some(onlyInstance) override def fieldEncoding(lte: LfTypeEncoding): view[lte.Field] = RecordView.Empty override def encoding(lte: LfTypeEncoding)(view: view[lte.Field]): lte.Out[T] = lte.emptyRecord(` dataTypeId`, () => onlyInstance) } }
Example 44
Source File: Namespace.scala From daml with Apache License 2.0 | 5 votes |
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved. // SPDX-License-Identifier: Apache-2.0 package com.daml.codegen.types import scala.language.higherKinds import scalaz.{Applicative, Comonad, Order, Traverse, ==>>} import scalaz.std.tuple._ import scalaz.syntax.apply._ import scalaz.syntax.bifunctor._ import scalaz.syntax.traverse._ def fromHierarchy[K: Order, V](elts: Traversable[(List[K], V)]): Namespace[K, Option[V]] = { val (subs, here) = elts partition (_._1.nonEmpty) Namespace( here.headOption map (_._2), ==>>(subs.groupBy(_._1.head).toSeq: _*) .map(children => fromHierarchy(children.map(_.leftMap(_.tail))))) } }
Example 45
Source File: TypeDeclOrTemplateWrapper.scala From daml with Apache License 2.0 | 5 votes |
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved. // SPDX-License-Identifier: Apache-2.0 package com.daml.codegen.dependencygraph import scala.language.higherKinds import com.daml.lf.iface.DefDataType import scalaz.{Applicative, Traverse} import scalaz.syntax.functor._ // wraps type declarations and templates so that they can be used together sealed abstract class TypeDeclOrTemplateWrapper[+TmplI] extends Product with Serializable object TypeDeclOrTemplateWrapper { implicit val `TD covariant`: Traverse[TypeDeclOrTemplateWrapper] = new Traverse[TypeDeclOrTemplateWrapper] { override def traverseImpl[G[_]: Applicative, A, B](fa: TypeDeclOrTemplateWrapper[A])( f: A => G[B]) = fa match { case fa @ TypeDeclWrapper(_) => Applicative[G].point(fa) case TemplateWrapper(t) => f(t) map (TemplateWrapper(_)) } } } final case class TypeDeclWrapper(typeDecl: DefDataType.FWT) extends TypeDeclOrTemplateWrapper[Nothing] final case class TemplateWrapper[+TmplI](template: TmplI) extends TypeDeclOrTemplateWrapper[TmplI]
Example 46
Source File: DependencyGraph.scala From daml with Apache License 2.0 | 5 votes |
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved. // SPDX-License-Identifier: Apache-2.0 package com.daml.codegen.dependencygraph import com.daml.lf.iface._ import com.daml.lf.iface.reader.InterfaceType import com.daml.lf.data.Ref.Identifier import com.daml.codegen.{Util, lf} import com.daml.lf.data.ImmArray.ImmArraySeq import lf.DefTemplateWithRecord import scalaz.std.list._ import scalaz.syntax.bifoldable._ import scalaz.syntax.foldable._ import scalaz.Bifoldable import scala.language.higherKinds sealed abstract class DependencyGraph[Iface, TmplI] { def orderedDependencies( library: Iface): OrderedDependencies[Identifier, TypeDeclOrTemplateWrapper[TmplI]] } private final case class LFDependencyGraph(private val util: lf.LFUtil) extends DependencyGraph[lf.LFUtil#Interface, lf.LFUtil#TemplateInterface] { def orderedDependencies(library: EnvironmentInterface) : OrderedDependencies[Identifier, TypeDeclOrTemplateWrapper[DefTemplateWithRecord.FWT]] = { val EnvironmentInterface(decls) = library // invariant: no type decl name equals any template alias val typeDeclNodes = decls.to[ImmArraySeq].collect { case (qualName, InterfaceType.Normal(typeDecl)) => ( qualName, Node( TypeDeclWrapper(typeDecl), symmGenTypeDependencies(typeDecl), collectDepError = false)) } val templateNodes = decls.to[ImmArraySeq].collect { case (qualName, InterfaceType.Template(typ, tpl)) => val recDeps = typ.foldMap(Util.genTypeTopLevelDeclNames) val choiceDeps = tpl.foldMap(Util.genTypeTopLevelDeclNames) ( qualName, Node( TemplateWrapper(DefTemplateWithRecord(typ, tpl)), recDeps ++ choiceDeps, collectDepError = true)) } Graph.cyclicDependencies(internalNodes = typeDeclNodes, roots = templateNodes) } private[this] def symmGenTypeDependencies[B[_, _]: Bifoldable]( gts: B[Type, Type]): List[Identifier] = gts.bifoldMap(Util.genTypeTopLevelDeclNames)(Util.genTypeTopLevelDeclNames) } object DependencyGraph { def apply(util: lf.LFUtil): DependencyGraph[util.Interface, util.TemplateInterface] = LFDependencyGraph(util) }
Example 47
Source File: ScopedDataType.scala From daml with Apache License 2.0 | 5 votes |
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved. // SPDX-License-Identifier: Apache-2.0 package com.daml.codegen package lf import com.daml.lf.data.ImmArray.ImmArraySeq import com.daml.lf.data.Ref import com.daml.lf.iface.{DataType, DefDataType} import scala.language.higherKinds import scalaz.{Apply, Comonad, Traverse1} import scalaz.syntax.functor._ final case class ScopedDataType[+DT]( name: ScopedDataType.Name, typeVars: ImmArraySeq[Ref.Name], dataType: DT) object ScopedDataType { type Name = Ref.Identifier type FWT = ScopedDataType[DataType.FWT] type DT[+RF, +VF] = ScopedDataType[DataType[RF, VF]] def fromDefDataType[RF, VF]( name: Ref.Identifier, ddt: DefDataType[RF, VF]): ScopedDataType[DataType[RF, VF]] = { val DefDataType(typeVars, dataType) = ddt apply(name, typeVars, dataType) } implicit val `SDT covariant`: Traverse1[ScopedDataType] with Comonad[ScopedDataType] = new Traverse1[ScopedDataType] with Comonad[ScopedDataType] { override def foldMapRight1[A, Z](fa: ScopedDataType[A])(z: A => Z)(f: (A, => Z) => Z): Z = z(fa.dataType) override def traverse1Impl[G[_]: Apply, A, B](fab: ScopedDataType[A])( f: A => G[B]): G[ScopedDataType[B]] = f(fab.dataType) map (b => fab copy (dataType = b)) override def copoint[A](p: ScopedDataType[A]): A = p.dataType override def cobind[A, B](fa: ScopedDataType[A])( f: ScopedDataType[A] => B): ScopedDataType[B] = fa copy (dataType = f(fa)) } }
Example 48
Source File: generics.scala From spark-tools with Apache License 2.0 | 5 votes |
package io.univalence.autobuild.struct import shapeless.labelled._ import shapeless._ import scala.collection.immutable import scala.language.higherKinds trait TypeName[T] { def name: String } object TypeName { import scala.reflect.runtime.universe.TypeTag implicit def fromTypeTag[T](implicit typeTag: TypeTag[T]): TypeName[T] = new TypeName[T] { override def name: String = typeTag.tpe.toString } } trait PathAwareness[T[_]] { def injectPrefix[A](prefix: String)(t: T[A]): T[A] } object DefaultPathAwareness { implicit def defaultPathAwareness[App[_]] = new PathAwareness[App] { override def injectPrefix[A](prefix: String)(t: App[A]): App[A] = t } } trait FieldsNonRecur[L] { def fieldnames: List[(String, String)] } trait LowPriorityFieldsNonRecur { implicit def caseClassFields[F, G]( implicit gen: LabelledGeneric.Aux[F, G], encode: Lazy[FieldsNonRecur[G]] ): FieldsNonRecur[F] = new FieldsNonRecur[F] { override def fieldnames: List[(String, String)] = encode.value.fieldnames } implicit def hcon[K <: Symbol, H, T <: HList]( implicit key: Witness.Aux[K], tv: TypeName[H], tailEncode: Lazy[FieldsNonRecur[T]] ): FieldsNonRecur[FieldType[K, H] :: T] = new FieldsNonRecur[FieldType[K, H] :: T] { override def fieldnames: List[(String, String)] = (key.value.name, tv.name) :: tailEncode.value.fieldnames } } object FieldsNonRecur extends LowPriorityFieldsNonRecur { implicit def hnil[L <: HNil]: FieldsNonRecur[L] = new FieldsNonRecur[L] { override def fieldnames: List[(String, String)] = Nil } def fieldnames[A](implicit tmr: FieldsNonRecur[A]): Seq[(String, String)] = tmr.fieldnames }
Example 49
Source File: IStep.scala From incubator-s2graph with Apache License 2.0 | 5 votes |
package org.apache.s2graph.core.step import org.apache.s2graph.core._ import rx.lang.scala.Observable import scala.language.higherKinds import scala.language.existentials trait RxStep[-A, +B] extends (A => Observable[B]) object RxStep { case class VertexFetchStep(g: S2GraphLike) extends RxStep[Seq[S2VertexLike], S2VertexLike] { override def apply(vertices: Seq[S2VertexLike]): Observable[S2VertexLike] = { Observable.from(vertices) } } case class EdgeFetchStep(g: S2GraphLike, qp: QueryParam) extends RxStep[S2VertexLike, S2EdgeLike] { override def apply(v: S2VertexLike): Observable[S2EdgeLike] = { implicit val ec = g.ec val step = org.apache.s2graph.core.Step(Seq(qp)) val q = Query(Seq(v), steps = Vector(step)) val f = g.getEdges(q).map { stepResult => val edges = stepResult.edgeWithScores.map(_.edge) Observable.from(edges) } Observable.from(f).flatten } } private def merge[A, B](steps: RxStep[A, B]*): RxStep[A, B] = new RxStep[A, B] { override def apply(in: A): Observable[B] = steps.map(_.apply(in)).toObservable.flatten } def toObservable(q: Query)(implicit graph: S2GraphLike): Observable[S2EdgeLike] = { val v1: Observable[S2VertexLike] = VertexFetchStep(graph).apply(q.vertices) val serialSteps = q.steps.map { step => val parallelSteps = step.queryParams.map(qp => EdgeFetchStep(graph, qp)) merge(parallelSteps: _*) } v1.flatMap { v => val initOpt = serialSteps.headOption.map(_.apply(v)) initOpt.map { init => serialSteps.tail.foldLeft(init) { case (prev, next) => prev.map(_.tgtForVertex).flatMap(next) } }.getOrElse(Observable.empty) } } }
Example 50
Source File: ParquetRecordDecoder.scala From parquet4s with MIT License | 5 votes |
package com.github.mjakubowski84.parquet4s import shapeless.labelled.{FieldType, field} import shapeless.{::, HList, HNil, LabelledGeneric, Lazy, Witness} import scala.language.higherKinds import scala.util.control.NonFatal def decode(record: RowParquetRecord, configuration: ValueCodecConfiguration): T } object ParquetRecordDecoder { object DecodingException { def apply(msg: String, cause: Throwable): DecodingException = { val decodingException = DecodingException(msg) decodingException.initCause(cause) decodingException } } case class DecodingException(msg: String) extends RuntimeException(msg) def apply[T](implicit ev: ParquetRecordDecoder[T]): ParquetRecordDecoder[T] = ev def decode[T](record: RowParquetRecord, configuration: ValueCodecConfiguration = ValueCodecConfiguration.default) (implicit ev: ParquetRecordDecoder[T]): T = ev.decode(record, configuration) implicit val nilDecoder: ParquetRecordDecoder[HNil] = new ParquetRecordDecoder[HNil] { override def decode(record: RowParquetRecord, configuration: ValueCodecConfiguration): HNil.type = HNil } implicit def headValueDecoder[FieldName <: Symbol, Head, Tail <: HList](implicit witness: Witness.Aux[FieldName], headDecoder: ValueCodec[Head], tailDecoder: ParquetRecordDecoder[Tail] ): ParquetRecordDecoder[FieldType[FieldName, Head] :: Tail] = new ParquetRecordDecoder[FieldType[FieldName, Head] :: Tail] { override def decode(record: RowParquetRecord, configuration: ValueCodecConfiguration): FieldType[FieldName, Head] :: Tail = { val fieldName = witness.value.name val decodedFieldValue = try { record.get[Head](fieldName, configuration) } catch { case NonFatal(cause) => throw DecodingException(s"Failed to decode field $fieldName of record: $record", cause) } field[FieldName](decodedFieldValue) :: tailDecoder.decode(record, configuration) } } implicit def genericDecoder[A, R](implicit gen: LabelledGeneric.Aux[A, R], decoder: Lazy[ParquetRecordDecoder[R]] ): ParquetRecordDecoder[A] = new ParquetRecordDecoder[A] { override def decode(record: RowParquetRecord, configuration: ValueCodecConfiguration): A = gen.from(decoder.value.decode(record, configuration)) } }
Example 51
Source File: ParquetRecordEncoder.scala From parquet4s with MIT License | 5 votes |
package com.github.mjakubowski84.parquet4s import shapeless.labelled.FieldType import shapeless.{::, HList, HNil, LabelledGeneric, Lazy, Witness} import scala.language.higherKinds import scala.util.control.NonFatal def encode(entity: T, configuration: ValueCodecConfiguration): RowParquetRecord } object ParquetRecordEncoder { object EncodingException { def apply(msg: String, cause: Throwable): EncodingException = { val encodingException = EncodingException(msg) encodingException.initCause(cause) encodingException } } case class EncodingException(msg: String) extends RuntimeException(msg) def apply[T](implicit ev: ParquetRecordEncoder[T]): ParquetRecordEncoder[T] = ev def encode[T](entity: T, configuration: ValueCodecConfiguration = ValueCodecConfiguration.default) (implicit ev: ParquetRecordEncoder[T]): RowParquetRecord = ev.encode(entity, configuration) implicit val nilDEncoder: ParquetRecordEncoder[HNil] = new ParquetRecordEncoder[HNil] { override def encode(nil: HNil, configuration: ValueCodecConfiguration): RowParquetRecord = RowParquetRecord() } implicit def headValueEncoder[FieldName <: Symbol, Head, Tail <: HList](implicit witness: Witness.Aux[FieldName], headEncoder: ValueCodec[Head], tailEncoder: ParquetRecordEncoder[Tail] ): ParquetRecordEncoder[FieldType[FieldName, Head] :: Tail] = new ParquetRecordEncoder[FieldType[FieldName, Head] :: Tail] { override def encode(entity: FieldType[FieldName, Head] :: Tail, configuration: ValueCodecConfiguration): RowParquetRecord = { val fieldName = witness.value.name val fieldValue = try { headEncoder.encode(entity.head, configuration) } catch { case NonFatal(cause) => throw EncodingException(s"Failed to encode field $fieldName: ${entity.head}, due to ${cause.getMessage}", cause) } tailEncoder.encode(entity.tail, configuration).prepend(fieldName, fieldValue) } } implicit def genericEncoder[A, R](implicit gen: LabelledGeneric.Aux[A, R], encoder: Lazy[ParquetRecordEncoder[R]] ): ParquetRecordEncoder[A] = new ParquetRecordEncoder[A] { override def encode(entity: A, configuration: ValueCodecConfiguration): RowParquetRecord = encoder.value.encode(gen.to(entity), configuration) } }
Example 52
Source File: CollectionTransformer.scala From parquet4s with MIT License | 5 votes |
package com.github.mjakubowski84.parquet4s import scala.language.{higherKinds, implicitConversions} import scala.reflect.ClassTag def to(list: List[Element]): Col[Element] } @deprecated(message = "This object is no longer in use", since = "1.2.0") object CollectionTransformer { implicit def seqTransformer[E]: CollectionTransformer[E, Seq] = new CollectionTransformer[E, Seq] { override def from(col: Seq[E]): List[E] = col.toList override def to(list: List[E]): Seq[E] = list } implicit def listTransformer[E]: CollectionTransformer[E, List] = new CollectionTransformer[E, List] { override def from(col: List[E]): List[E] = col override def to(list: List[E]): List[E] = list } implicit def vectorTransformer[E]: CollectionTransformer[E, Vector] = new CollectionTransformer[E, Vector] { override def from(col: Vector[E]): List[E] = col.toList override def to(list: List[E]): Vector[E] = list.toVector } implicit def setTransformer[E]: CollectionTransformer[E, Set] = new CollectionTransformer[E, Set] { override def from(col: Set[E]): List[E] = col.toList override def to(list: List[E]): Set[E] = list.toSet } implicit def arrayTransformer[E : ClassTag]: CollectionTransformer[E, Array] = new CollectionTransformer[E, Array] { override def from(col: Array[E]): List[E] = col.toList override def to(list: List[E]): Array[E] = list.toArray } }
Example 53
Source File: MonadlessMonad.scala From monadless with Apache License 2.0 | 5 votes |
package io.monadless.algebird import scala.language.higherKinds import com.twitter.algebird.Monad trait MonadlessMonad[M[_]] extends MonadlessApplicative[M] { override protected val tc: Monad[M] def flatMap[T, U](m: M[T])(f: T => M[U]): M[U] = tc.flatMap(m)(f) } object MonadlessMonad { def apply[M[_]]()(implicit a: Monad[M]) = new MonadlessMonad[M] { override protected val tc = a } }
Example 54
Source File: package.scala From magnolify with Apache License 2.0 | 5 votes |
package magnolify import scala.collection.generic.CanBuildFrom import scala.collection.mutable import scala.language.higherKinds import scala.reflect.ClassTag import scala.util.hashing.MurmurHash3 package object shims { trait Monadic[F[_]] extends mercator.Monadic[F] { def flatMapS[A, B](from: F[A])(fn: A => F[B]): F[B] def mapS[A, B](from: F[A])(fn: A => B): F[B] override def flatMap[A, B](from: F[A])(fn: A => F[B]): F[B] = flatMapS(from)(fn) override def map[A, B](from: F[A])(fn: A => B): F[B] = mapS(from)(fn) } trait FactoryCompat[-A, +C] extends Serializable { def newBuilder: mutable.Builder[A, C] def build(xs: TraversableOnce[A]): C = (newBuilder ++= xs).result() } object FactoryCompat extends LowPriorityFactoryCompat1 { private type FC[A, C] = FactoryCompat[A, C] def apply[A, C](f: () => mutable.Builder[A, C]): FC[A, C] = new FactoryCompat[A, C] { override def newBuilder: mutable.Builder[A, C] = f() } implicit def arrayFC[A: ClassTag] = FactoryCompat(() => Array.newBuilder[A]) // Deprecated in 2.13 // implicit def traversableFC[A] = FactoryCompat(() => Traversable.newBuilder[A]) // List <: Iterable // implicit def iterableFC[A] = FactoryCompat(() => Iterable.newBuilder[A]) // List <: Seq // implicit def seqFC[A] = FactoryCompat(() => Seq.newBuilder[A]) // Vector <: IndexedSeq // implicit def indexedSeqFC[A] = FactoryCompat(() => IndexedSeq.newBuilder[A]) } trait LowPriorityFactoryCompat1 extends LowPriorityFactoryCompat2 { implicit def listFC[A] = FactoryCompat(() => List.newBuilder[A]) } trait LowPriorityFactoryCompat2 { implicit def vectorFC[A] = FactoryCompat(() => Vector.newBuilder[A]) // Deprecated in 2.13 // implicit def streamFC[A] = FactoryCompat(() => Stream.newBuilder[A]) } object SerializableCanBuildFroms { private def cbf[A, C](f: () => mutable.Builder[A, C]): CanBuildFrom[C, A, C] = new CanBuildFrom[C, A, C] with Serializable { override def apply(from: C): mutable.Builder[A, C] = f() override def apply(): mutable.Builder[A, C] = f() } implicit def arrayCBF[A: ClassTag] = cbf(() => Array.newBuilder[A]) implicit def traversableCBF[A] = cbf(() => Traversable.newBuilder[A]) implicit def iterableCBF[A] = cbf(() => Iterable.newBuilder[A]) implicit def seqCBF[A] = cbf(() => Seq.newBuilder[A]) implicit def indexedSeqCBF[A] = cbf(() => IndexedSeq.newBuilder[A]) implicit def listCBF[A] = cbf(() => List.newBuilder[A]) implicit def vectorCBF[A] = cbf(() => Vector.newBuilder[A]) implicit def streamCBF[A] = cbf(() => Stream.newBuilder[A]) } val JavaConverters = scala.collection.JavaConverters object MurmurHash3Compat { def seed(data: Int): Int = MurmurHash3.productSeed } }
Example 55
Source File: Model.scala From spatial with MIT License | 5 votes |
package models import scala.language.higherKinds case class Model[T,F[A]<:Fields[A,F]](name: String, params: Seq[String], entries: Map[String,T])(implicit val config: F[T]) { def fullName: String = name + "_" + params.mkString("_") private val fields: Array[String] = config.fields private val default: T = config.default def keys: Array[String] = fields def nonZeroFields: Array[String] = fields.filter{f => entries.contains(f) && entries(f) != default } // HACK - get parameter which gives number def n: Option[Int] = { val i = params.lastIndexWhere(_ != "") if (i >= 0) { val x = params(i) if (x.nonEmpty && x.forall(_.isDigit)) Some(x.toInt) else None } else None } def renameEntries(remapping: String => String): Model[T,F] = { val entries2 = entries.map{case (k,v) => remapping(k) -> v } new Model[T,F](name, params, entries2) } def toSeq: Seq[T] = fields.map{f => this.apply(f) } def apply(field: String): T = entries.getOrElse(field, default) def seq(keys: String*): Seq[T] = keys.map{k => this(k)} def foreach(func: (String,T) => Unit): Unit = entries.foreach{case (k,v) => func(k,v) } def map[R](func: T => R)(implicit config: F[R]): Model[R,F] = { new Model[R,F](name, params, entries.map{case (k,v) => k -> func(v)}) } def zip[S,R](that: Model[S,F])(func: (T,S) => R)(implicit config: F[R]): Model[R,F] = { new Model[R,F](name, params, fields.map{k => k -> func(this(k), that(k)) }.toMap) } def zipExists(that: Model[T,F])(func: (T,T) => Boolean): Boolean = fields.exists{k => func(this(k), that(k)) } def zipForall(that: Model[T,F])(func: (T,T) => Boolean): Boolean = fields.forall{k => func(this(k), that(k)) } def +(that: Model[T,F])(implicit num: AffArith[T]): Model[T,F] = this.zip(that){(a,b) => num.plus(a,b) } def -(that: Model[T,F])(implicit num: AffArith[T]): Model[T,F] = this.zip(that){(a,b) => num.minus(a,b) } def /(that: Model[Double,F])(implicit num: AffArith[T]): Model[T,F] = this.zip(that){(a,b) => num.div(a,b) } def *(b: Double)(implicit num: AffArith[T]): Model[T,F] = this.map{x => num.times(x,b) } def /(b: Double)(implicit num: AffArith[T]): Model[T,F] = this.map{x => num.div(x,b) } def isNonZero(implicit num: Numeric[T], ord: Ordering[T]): Boolean = this.toSeq.exists{x => ord.gt(x, num.fromInt(0)) } def <(that: Model[T,F])(implicit ord: Ordering[T]): Boolean = this.zipForall(that){(a,b) => ord.lt(a,b) } // a0 < b0 && ... && aN < bN def <=(that: Model[T,F])(implicit ord: Ordering[T]): Boolean = this.zipForall(that){(a,b) => ord.lteq(a,b) } // a0 <= b0 && ... && aN <= bN // These may seem a bit odd, but required to have the property !(a < b) = a >= b def >(that: Model[T,F])(implicit ord: Ordering[T]): Boolean = this.zipExists(that){(a,b) => ord.gt(a,b) } // a0 > b0 || ... || aN > b0 def >=(that: Model[T,F])(implicit ord: Ordering[T]): Boolean = this.zipExists(that){(a,b) => ord.gteq(a,b) } // a0 >= b0 || ... || aN >= b0 // Alternative comparisons, where < is true if any is less than, > is true iff all are greater def <<(that: Model[T,F])(implicit ord: Ordering[T]): Boolean = this.zipExists(that){(a,b) => ord.lt(a,b) } def <<=(that: Model[T,F])(implicit ord: Ordering[T]): Boolean = this.zipExists(that){(a,b) => ord.lteq(a,b) } def >>(that: Model[T,F])(implicit ord: Ordering[T]): Boolean = this.zipForall(that){(a,b) => ord.gt(a,b) } def >>=(that: Model[T,F])(implicit ord: Ordering[T]): Boolean = this.zipForall(that){(a,b) => ord.gteq(a,b) } override def toString: String = { name + fields.map{f => f -> this(f) } .filterNot(_._2 == default) .map{case (f,v) => s"$f=$v"} .mkString("(", ", ", ")") } def toPrintableString(nParams: Int): String = { val padParams = Array.fill(nParams - params.length)("") val seq = this.toSeq (Array(name) ++ params ++ padParams ++ seq).mkString(",") } } object Model { def zero[T,C[A]<:Fields[A,C]](implicit config: C[T]): Model[T,C] = new Model[T,C]("", Nil, Map.empty) def apply[T,C[A]<:Fields[A,C]](entries: (String,T)*)(implicit config: C[T]): Model[T,C] = new Model[T,C]("", Nil, entries.toMap) def fromArray[T,C[A]<:Fields[A,C]](name: String, params: Seq[String], entries: Array[T])(implicit config: C[T]): Model[T,C] = { new Model[T,C](name, params, config.fields.zip(entries).toMap) } }
Example 56
Source File: Fields.scala From spatial with MIT License | 5 votes |
package models import scala.language.higherKinds trait Fields[T,M[_]<:Fields[_,M]] { def fields: Array[String] def default: T def convert[B](d: B): M[B] } case class AreaFields[T](fields: Array[String], default: T) extends Fields[T,AreaFields] { def convert[B](d: B): AreaFields[B] = AreaFields[B](fields, d) } case class LatencyFields[T](fields: Array[String], default: T) extends Fields[T,LatencyFields] { def convert[B](d: B): LatencyFields[B] = LatencyFields(fields, d) }
Example 57
Source File: package.scala From spatial with MIT License | 5 votes |
import scala.language.higherKinds package object models { type NodeModel = Either[LinearModel,Double] type Area = Model[Double,AreaFields] type Latency = Model[Double,LatencyFields] type NodeArea = Model[NodeModel,AreaFields] type NodeLatency = Model[NodeModel,LatencyFields] object Area { def empty[T](implicit c: AreaFields[T]) = new Model[T,AreaFields]("",Nil,Map.empty) def apply[T](entries: (String,T)*)(implicit c: AreaFields[T]): Model[T,AreaFields] = { new Model[T,AreaFields]("",Nil,entries.toMap) } def fromArray[T](name: String, params: Seq[String], entries: Array[T])(implicit config: AreaFields[T]): Model[T,AreaFields] = { new Model[T,AreaFields](name, params, config.fields.zip(entries).toMap) } } object Latency { def empty[T](implicit c: LatencyFields[T]) = new Model[T,LatencyFields]("",Nil,Map.empty) def apply[T](entries: (String,T)*)(implicit c: LatencyFields[T]): Model[T,LatencyFields] = { new Model[T,LatencyFields]("",Nil,entries.toMap) } def fromArray[T](name: String, params: Seq[String], entries: Array[T])(implicit config: LatencyFields[T]): Model[T,LatencyFields] = { new Model[T,LatencyFields](name, params, config.fields.zip(entries).toMap) } } implicit class NodeModelOps(x: NodeModel) { def eval(args: (String,Double)*): Double = x match { case Left(model) => Math.max(0.0, model.eval(args:_*)) case Right(num) => Math.max(0.0, num) } } implicit class SeqAreaOps[T,C[A]<:Fields[A,C]](areas: Seq[Model[T,C]]) { def getFirst(name: String, params: (Int,String)*): Model[T,C] = { areas.find{a => a.name == name && params.forall{case (i,p) => a.params(i) == p} }.get } def getAll(name: String, params: (Int,String)*): Seq[Model[T,C]] = { areas.filter{a: Model[T,C] => a.name == name && params.forall{case (i,p) => a.params(i) == p} } } } implicit class DoubleModelOps[C[A]<:Fields[A,C]](a: Model[Double,C]) { implicit val lin: C[LinearModel] = a.config.convert(d = LinearModel(Nil,Set.empty)) implicit val dbl: C[Double] = a.config def cleanup: Model[Double,C] = a.map{x => Math.max(0.0, Math.round(x)) } def fractional: Model[Double,C] = a.map{x => Math.max(0.0, x) } } implicit class LinearModelAreaOps[C[A]<:Fields[A,C]](a: Model[LinearModel,C]) { implicit val lin: C[LinearModel] = a.config implicit val dbl: C[Double] = a.config.convert(d = 0.0) def *(b: String): Model[LinearModel,C] = a.map(_*b) def *(b: Double): Model[LinearModel,C] = a.map(_*b) def /(b: Double): Model[LinearModel,C] = a.map(_/b) def +(b: Double): Model[LinearModel,C] = a.map(_+b) def -(b: Double): Model[LinearModel,C] = a.map(_-b) def ++(b: Model[LinearModel,C]): Model[LinearModel,C] = a.zip(b){(x,y) => x + y } def --(b: Model[LinearModel,C]): Model[LinearModel,C] = a.zip(b){(x,y) => x - y } def <->(b: Model[LinearModel,C]): Model[LinearModel,C] = a.zip(b){(x,y) => x <-> y } def apply(xs: (String,Double)*): Model[Double,C] = a.map(_.eval(xs:_*)) def eval(xs: (String,Double)*): Model[Double,C] = a.map(_.eval(xs:_*)) def partial(xs: (String,Double)*): Model[LinearModel,C] = a.map(_.partial(xs:_*)) def cleanup: Model[LinearModel,C] = a.map(_.cleanup) def fractional: Model[LinearModel,C] = a.map(_.fractional) } implicit class ModelNodeModelOps[C[A]<:Fields[A,C]](a: Model[NodeModel,C]) { implicit val dbl: C[Double] = a.config.convert(d = 0.0) def apply(xs: (String,Double)*): Model[Double,C] = a.map{nm => nm.eval(xs:_*) } def eval(xs: (String,Double)*): Model[Double,C] = a.map(_.eval(xs:_*)) } }
Example 58
Source File: AsyncValidationRules.scala From octopus with Apache License 2.0 | 5 votes |
package octopus import octopus.AsyncValidatorM.instance import shapeless.{::, Generic, HNil} import scala.language.higherKinds import scala.reflect.ClassTag import scala.util.control.NonFatal object AsyncValidationRules extends Serializable { def rule[M[_]: AppError, T](asyncPred: T => M[Boolean], whenInvalid: String): AsyncValidatorM[M, T] = instance { obj: T => AppError[M].map(asyncPred(obj))(if(_) Nil else List(ValidationError(whenInvalid))) } def ruleVC[M[_]: AppError, T, V](asyncPred: V => M[Boolean], whenInvalid: String) (implicit gen: Generic.Aux[T, V :: HNil]): AsyncValidatorM[M, T] = instance { obj: T => rule[M, V](asyncPred, whenInvalid) .validate(gen.to(obj).head) } def ruleCatchOnly[M[_]: AppError, T, E <: Throwable : ClassTag](asyncPred: T => M[Boolean], whenInvalid: String, whenCaught: E => String): AsyncValidatorM[M, T] = instance { obj: T => AppError[M].recover( try { rule(asyncPred, whenInvalid).validate(obj) } catch { case NonFatal(ex) => AppError[M].failed(ex) }, { case ex if implicitly[ClassTag[E]].runtimeClass.isInstance(ex) => List(ValidationError(whenCaught(ex.asInstanceOf[E]))) } ) } def ruleCatchNonFatal[M[_]: AppError, T](asyncPred: T => M[Boolean], whenInvalid: String, whenCaught: Throwable => String): AsyncValidatorM[M, T] = instance { obj: T => AppError[M].recover( try { rule(asyncPred, whenInvalid).validate(obj) } catch { case NonFatal(ex) => AppError[M].failed(ex) }, { case NonFatal(ex) => List(ValidationError(whenCaught(ex))) } ) } def ruleEither[M[_]: AppError, T](asyncPred: T => M[Either[String, Boolean]], whenInvalid: String): AsyncValidatorM[M, T] = instance { obj: T => AppError[M].map(asyncPred(obj)) { case Right(true) => Nil case Right(false) => List(ValidationError(whenInvalid)) case Left(why) => List(ValidationError(why)) } } def ruleOption[M[_]: AppError, T](asyncPred: T => M[Option[Boolean]], whenInvalid: String, whenNone: String): AsyncValidatorM[M, T] = instance { obj: T => AppError[M].map(asyncPred(obj)) { case Some(true) => Nil case Some(false) => List(ValidationError(whenInvalid)) case None => List(ValidationError(whenNone)) } } }
Example 59
Source File: DslMacros.scala From octopus with Apache License 2.0 | 5 votes |
package octopus import scala.language.higherKinds private[octopus] object DslMacros extends Serializable { def ruleFieldSelector[T: c.WeakTypeTag, F: c.WeakTypeTag](c: scala.reflect.macros.blackbox.Context) (selector: c.Expr[T => F], pred: c.Expr[F => Boolean], whenInvalid: c.Expr[String]): c.Expr[Validator[T]] = { import c.universe._ selector.tree match { case q"($_) => $_.${fieldName: Name}" => val fieldSymbol = Symbol(fieldName.decodedName.toString) val T = weakTypeOf[T] val F = weakTypeOf[F] val obj = TermName(c.freshName("obj")) c.Expr[Validator[T]] { q""" {${c.prefix}}.compose { _root_.octopus.Validator.instance[$T] { ($obj: $T) => _root_.octopus.ValidationRules .rule[$F]($pred, $whenInvalid) .validate($selector($obj)) .map(_root_.octopus.FieldLabel($fieldSymbol) :: _) } } """ } case t => c.abort(c.enclosingPosition, s"Invalid selector: $t!") } } def ruleFieldSelectorAsync[M[_], T: c.WeakTypeTag, F: c.WeakTypeTag](c: scala.reflect.macros.blackbox.Context) (selector: c.Expr[T => F], pred: c.Expr[F => M[Boolean]], whenInvalid: c.Expr[String])(implicit M: c.WeakTypeTag[M[_]]): c.Expr[AsyncValidatorM[M, T]] = { import c.universe._ selector.tree match { case q"($_) => $_.${fieldName: Name}" => val fieldSymbol = Symbol(fieldName.decodedName.toString) val T = weakTypeOf[T] val F = weakTypeOf[F] val obj = TermName(c.freshName("obj")) c.Expr[AsyncValidatorM[M, T]] { q""" {${c.prefix}}.compose { _root_.octopus.AsyncValidatorM.instance[$M, $T] { ($obj: $T) => _root_.octopus.AppError[$M].map( _root_.octopus.AsyncValidationRules .rule[$M, $F]($pred, $whenInvalid) .validate($selector($obj)) ){ errs => errs.map(_root_.octopus.FieldLabel($fieldSymbol) :: _) } } } """ } case t => c.abort(c.enclosingPosition, s"Invalid selector: $t!") } } def ruleFieldSelectorSync[M[_], T: c.WeakTypeTag, F: c.WeakTypeTag](c: scala.reflect.macros.blackbox.Context) (selector: c.Expr[T => F], pred: c.Expr[F => Boolean], whenInvalid: c.Expr[String]): c.Expr[AsyncValidatorM[M, T]] = { import c.universe._ selector.tree match { case q"($_) => $_.${fieldName: Name}" => val fieldSymbol = Symbol(fieldName.decodedName.toString) val T = weakTypeOf[T] val F = weakTypeOf[F] val obj = TermName(c.freshName("obj")) c.Expr[AsyncValidatorM[M, T]] { q""" {${c.prefix}}.compose { _root_.octopus.Validator.instance[$T] { ($obj: $T) => _root_.octopus.ValidationRules .rule[$F]($pred, $whenInvalid) .validate($selector($obj)) .map(_root_.octopus.FieldLabel($fieldSymbol) :: _) } } """ } case t => c.abort(c.enclosingPosition, s"Invalid selector: $t!") } } }
Example 60
Source File: AsyncValidators.scala From octopus with Apache License 2.0 | 5 votes |
package octopus.example.domain import octopus.dsl._ import octopus.{AppError, AsyncValidatorM} import scala.language.higherKinds trait EmailService[M[_]] { def isEmailTaken(email: String): M[Boolean] def doesDomainExists(email: String): M[Boolean] } trait GeoService[M[_]] { def doesPostalCodeExist(postalCode: PostalCode.T): M[Boolean] def isPostalCodeValidForCity(postalCode: PostalCode.T, city: String): M[Boolean] } class AsyncValidators[M[_]: AppError](emailService: EmailService[M], geoService: GeoService[M]) { val Email_Err_AlreadyTaken = "email is already taken by someone else" val Email_Err_DomainDoesNotExists = "domain does not exists" implicit val emailAsyncValidator: AsyncValidatorM[M, Email] = Validator .derived[Email] .asyncM[M].ruleVC(emailService.isEmailTaken, Email_Err_AlreadyTaken) .async.rule(_.address, emailService.doesDomainExists, Email_Err_DomainDoesNotExists) .rule(_.address, (_: String).nonEmpty, Email.Err_MustNotBeEmpty) // repeated to check dsl behavior & to ensure that it keep the validator in the asynchronous world val PostalCode_Err_DoesNotExist = "postal code does not exist" implicit val postalCodeAsyncValidator: AsyncValidatorM[M, PostalCode.T] = AsyncValidatorM[M, PostalCode.T] .async.rule(geoService.doesPostalCodeExist, PostalCode_Err_DoesNotExist) val PostalCode_Err_NotValidForCity = "postal code is not valid for the city" implicit val addressValidator: AsyncValidatorM[M, Address] = Validator[Address] .asyncM[M].ruleCatchNonFatal(addr => geoService.isPostalCodeValidForCity(addr.postalCode, addr.city), PostalCode_Err_NotValidForCity, _.getMessage) .async.composeDerived }
Example 61
Source File: ToFuture.scala From octopus with Apache License 2.0 | 5 votes |
package octopus.async import scala.concurrent.Future import scala.language.higherKinds trait ToFuture[F[_]] { def toFuture[A](value: F[A]): Future[A] } object ToFuture { implicit val futureInstance: ToFuture[Future] = new ToFuture[Future] { def toFuture[A](value: Future[A]): Future[A] = value } object syntax { implicit class ToFutureOps[F[_]: ToFuture, A](value: F[A]) { def toFuture(): Future[A] = implicitly[ToFuture[F]].toFuture(value) } } }
Example 62
Source File: package.scala From featherbed with Apache License 2.0 | 5 votes |
package featherbed import scala.annotation.implicitNotFound import scala.language.higherKinds import cats.data.Validated.Valid import com.twitter.finagle.http.Response import shapeless._ package object support { @implicitNotFound("""In order to decode a request to ${A}, it must be known that a decoder exists to ${A} from all the content types that you Accept, which is currently ${ContentTypes}. You may have forgotten to specify Accept types with the `accept(..)` method, or you may be missing Decoder instances for some content types. """) sealed trait DecodeAll[A, ContentTypes <: Coproduct] { val instances: List[content.Decoder.Aux[_, A]] def findInstance(ct: String): Option[content.Decoder.Aux[_, A]] = instances.find(_.contentType == ct) orElse instances.find(_.contentType == "**" def apply(response: Response) = Valid(response) } :: Nil } } }
Example 63
Source File: CompanionSorter.scala From mango with Apache License 2.0 | 5 votes |
package com.kakao.shaded.jackson.module.scala.util import collection.mutable.{ArrayBuffer, ListBuffer} import collection.GenTraversable import collection.generic.GenericCompanion import scala.reflect.ClassTag import scala.language.higherKinds class CompanionSorter[CC[X] <: GenTraversable[X]] { type HKClassManifest[CC2[_]] = ClassTag[CC2[_]] private[this] val companions = new ArrayBuffer[(Class[_], GenericCompanion[CC])]() def add[T[X] <: CC[X] : HKClassManifest](companion: GenericCompanion[T]): CompanionSorter[CC] = { companions += implicitly[HKClassManifest[T]].runtimeClass -> companion this } def toList: List[(Class[_], GenericCompanion[CC])] = { val cs = companions.toArray val output = new ListBuffer[(Class[_], GenericCompanion[CC])]() val remaining = cs.map(_ => 1) val adjMatrix = Array.ofDim[Int](cs.length, cs.length) // Build the adjacency matrix. Only mark the in-edges. for (i <- 0 until cs.length; j <- 0 until cs.length) { val (ic, _) = cs(i) val (jc, _) = cs(j) if (i != j && ic.isAssignableFrom(jc)) { adjMatrix(i)(j) = 1 } } // While we haven't removed every node, remove all nodes with 0 degree in-edges. while (output.length < cs.length) { val startLength = output.length for (i <- 0 until cs.length) { if (remaining(i) == 1 && dotProduct(adjMatrix(i), remaining) == 0) { output += companions(i) remaining(i) = 0 } } // If we couldn't remove any nodes, it means we've found a cycle. Realistically this should never happen. if (output.length == startLength) { throw new IllegalStateException("Companions contain a cycle.") } } output.toList } private[this] def dotProduct(a: Array[Int], b: Array[Int]): Int = { if (a.length != b.length) throw new IllegalArgumentException() (0 until a.length).map(i => a(i) * b(i)).sum } }
Example 64
Source File: Functors.scala From play-json with Apache License 2.0 | 5 votes |
package play.api.libs.functional import scala.language.higherKinds sealed trait Variant[M[_]] trait Functor[M[_]] extends Variant[M] { def fmap[A, B](m: M[A], f: A => B): M[B] } object Functor { implicit val functorOption: Functor[Option] = new Functor[Option] { def fmap[A, B](a: Option[A], f: A => B): Option[B] = a.map(f) } } trait InvariantFunctor[M[_]] extends Variant[M] { def inmap[A, B](m: M[A], f1: A => B, f2: B => A): M[B] } trait ContravariantFunctor[M[_]] extends Variant[M] { def contramap[A, B](m: M[A], f1: B => A): M[B] } class FunctorOps[M[_], A](ma: M[A])(implicit fu: Functor[M]) { def fmap[B](f: A => B): M[B] = fu.fmap(ma, f) } class ContravariantFunctorOps[M[_], A](ma: M[A])(implicit fu: ContravariantFunctor[M]) { def contramap[B](f: B => A): M[B] = fu.contramap(ma, f) } class InvariantFunctorOps[M[_], A](ma: M[A])(implicit fu: InvariantFunctor[M]) { def inmap[B](f: A => B, g: B => A): M[B] = fu.inmap(ma, f, g) } // Work around the fact that Scala does not support higher-kinded type patterns (type variables can only be simple identifiers) // We use case classes wrappers so we can pattern match using their extractor sealed trait VariantExtractor[M[_]] case class FunctorExtractor[M[_]](functor: Functor[M]) extends VariantExtractor[M] case class InvariantFunctorExtractor[M[_]](InvariantFunctor: InvariantFunctor[M]) extends VariantExtractor[M] case class ContravariantFunctorExtractor[M[_]](ContraVariantFunctor: ContravariantFunctor[M]) extends VariantExtractor[M] object VariantExtractor { implicit def functor[M[_]: Functor]: FunctorExtractor[M] = FunctorExtractor(implicitly[Functor[M]]) implicit def contravariantFunctor[M[_]: ContravariantFunctor]: ContravariantFunctorExtractor[M] = ContravariantFunctorExtractor(implicitly[ContravariantFunctor[M]]) implicit def invariantFunctor[M[_]: InvariantFunctor]: InvariantFunctorExtractor[M] = InvariantFunctorExtractor(implicitly[InvariantFunctor[M]]) }
Example 65
Source File: Alternative.scala From play-json with Apache License 2.0 | 5 votes |
package play.api.libs.functional import scala.language.higherKinds trait Alternative[M[_]] { def app: Applicative[M] def |[A, B >: A](alt1: M[A], alt2: M[B]): M[B] def empty: M[Nothing] //def some[A](m: M[A]): M[List[A]] //def many[A](m: M[A]): M[List[A]] } class AlternativeOps[M[_], A](alt1: M[A])(implicit a: Alternative[M]) { def |[B >: A](alt2: M[B]): M[B] = a.|(alt1, alt2) def or[B >: A](alt2: M[B]): M[B] = |(alt2) }
Example 66
Source File: Applicative.scala From play-json with Apache License 2.0 | 5 votes |
package play.api.libs.functional import scala.language.higherKinds trait Applicative[M[_]] extends DeprecatedApplicative[M] { def pure[A](f: => A): M[A] def map[A, B](m: M[A], f: A => B): M[B] def apply[A, B](mf: M[A => B], ma: M[A]): M[B] } sealed trait DeprecatedApplicative[M[_]] { _: Applicative[M] => @deprecated("Use `pure` with `f:=>A` parameter", "2.7.0") def pure[A](value: A): M[A] = pure(f = value) } object Applicative { implicit val applicativeOption: Applicative[Option] = new Applicative[Option] { def pure[A](f: => A): Option[A] = Option(f) def map[A, B](m: Option[A], f: A => B): Option[B] = m.map(f) def apply[A, B](mf: Option[A => B], ma: Option[A]): Option[B] = mf.flatMap(f => ma.map(f)) } } class ApplicativeOps[M[_], A](ma: M[A])(implicit a: Applicative[M]) { def ~>[B](mb: M[B]): M[B] = a(a(a.pure(f = { _: A => (b: B) => b }), ma), mb) def andKeep[B](mb: M[B]): M[B] = ~>(mb) def <~[B](mb: M[B]): M[A] = a(a(a.pure(f = { a: A => (_: B) => a }), ma), mb) def keepAnd[B](mb: M[B]): M[A] = <~(mb) def <~>[B, C](mb: M[B])(implicit witness: <:<[A, B => C]): M[C] = apply(mb) def apply[B, C](mb: M[B])(implicit witness: <:<[A, B => C]): M[C] = a(a.map(ma, witness), mb) }
Example 67
Source File: RecoverOps.scala From play-json-ops with MIT License | 5 votes |
package play.api.libs.json.ops.v4 import play.api.data.validation.ValidationError import play.api.libs.json._ import scala.language.higherKinds import scala.reflect.ClassTag import scala.util.control.NonFatal trait RecoverOps[F[x] <: Reads[x], A] extends Any { def unsafeReader: Reads[A] def expectedTypeError(cls: Class[_], args: Any*): JsError = { expectedTypeError(safeSimpleClassName(cls), args: _*) } } class ReadsRecoverOps[A](override val unsafeReader: Reads[A]) extends AnyVal with RecoverOps[Reads, A] { final override protected def build(safeReader: Reads[A]): Reads[A] = safeReader } class FormatRecoverOps[A](val unsafeFormat: Format[A]) extends AnyVal with RecoverOps[Format, A] { final override def unsafeReader: Reads[A] = unsafeFormat final override protected def build(safeReader: Reads[A]): Format[A] = Format(safeReader, unsafeFormat) } class OFormatRecoverOps[A](val unsafeFormat: OFormat[A]) extends AnyVal with RecoverOps[OFormat, A] { final override def unsafeReader: Reads[A] = unsafeFormat final override protected def build(safeReader: Reads[A]): OFormat[A] = OFormat(safeReader, unsafeFormat) }
Example 68
Source File: RecoverOps.scala From play-json-ops with MIT License | 5 votes |
package play.api.libs.json.ops.v4 import play.api.libs.json._ import scala.language.higherKinds import scala.reflect.ClassTag import scala.util.control.NonFatal trait RecoverOps[F[x] <: Reads[x], A] extends Any { def unsafeReader: Reads[A] def recoverWith( recoverFn: PartialFunction[Throwable, JsResult[A]] ): Reads[A] = build { Reads { json: JsValue => try { unsafeReader.reads(json) } catch { case NonFatal(ex) if recoverFn isDefinedAt ex => recoverFn(ex) } } } // Subclasses need to define how to build an instance of F[A] from a Reads[A] protected def build(safeReader: Reads[A]): F[A] } class ReadsRecoverOps[A](override val unsafeReader: Reads[A]) extends AnyVal with RecoverOps[Reads, A] { final override protected def build(safeReader: Reads[A]): Reads[A] = safeReader } class FormatRecoverOps[A](val unsafeFormat: Format[A]) extends AnyVal with RecoverOps[Format, A] { final override def unsafeReader: Reads[A] = unsafeFormat final override protected def build(safeReader: Reads[A]): Format[A] = Format(safeReader, unsafeFormat) } class OFormatRecoverOps[A](val unsafeFormat: OFormat[A]) extends AnyVal with RecoverOps[OFormat, A] { final override def unsafeReader: Reads[A] = unsafeFormat final override protected def build(safeReader: Reads[A]): OFormat[A] = OFormat(safeReader, unsafeFormat) }
Example 69
Source File: RecoverOps.scala From play-json-ops with MIT License | 5 votes |
package play.api.libs.json.ops.v4 import play.api.libs.json._ import scala.language.higherKinds import scala.reflect.ClassTag import scala.util.control.NonFatal trait RecoverOps[F[x] <: Reads[x], A] extends Any { def unsafeReader: Reads[A] def expectedTypeError(cls: Class[_], args: Any*): JsError = { expectedTypeError(safeSimpleClassName(cls), args: _*) } } class ReadsRecoverOps[A](override val unsafeReader: Reads[A]) extends AnyVal with RecoverOps[Reads, A] { final override protected def build(safeReader: Reads[A]): Reads[A] = safeReader } class FormatRecoverOps[A](val unsafeFormat: Format[A]) extends AnyVal with RecoverOps[Format, A] { final override def unsafeReader: Reads[A] = unsafeFormat final override protected def build(safeReader: Reads[A]): Format[A] = Format(safeReader, unsafeFormat) } class OFormatRecoverOps[A](val unsafeFormat: OFormat[A]) extends AnyVal with RecoverOps[OFormat, A] { final override def unsafeReader: Reads[A] = unsafeFormat final override protected def build(safeReader: Reads[A]): OFormat[A] = OFormat(safeReader, unsafeFormat) }
Example 70
Source File: HttpContext.scala From airframe with Apache License 2.0 | 5 votes |
package wvlet.airframe.http import wvlet.airframe.http.HttpMessage.{Request, Response} import scala.concurrent.Future import scala.language.higherKinds override def apply( request: Request ): Future[Response] = ??? override def setThreadLocal[A](key: String, value: A): Unit = { // no-op } override def getThreadLocal[A](key: String): Option[A] = None } } }
Example 71
Source File: HttpFilter.scala From airframe with Apache License 2.0 | 5 votes |
package wvlet.airframe.http import scala.language.higherKinds trait HttpFilterType trait HttpFilter[Req, Resp, F[_]] extends HttpFilterType { self => type Filter = HttpFilter[Req, Resp, F] type Context = HttpContext[Req, Resp, F] protected def backend: HttpBackend[Req, Resp, F] protected def toFuture[A](v: A): F[A] = backend.toFuture(v) // Implementation to process the request. If this filter doesn't return any response, pass the request to the context(request) def apply(request: Req, context: Context): F[Resp] // Add another filter def andThen(nextFilter: Filter): Filter = new HttpFilter.AndThen[Req, Resp, F](backend, this, nextFilter) // End the filter chain with the given HttpContext def andThen(context: Context): Context = { new HttpContext.FilterAndThenContext[Req, Resp, F](backend, this, context) } } object HttpFilter { def newFilter[Req, Resp, F[_]]( baseBackend: HttpBackend[Req, Resp, F], body: (Req, HttpContext[Req, Resp, F]) => F[Resp] ): HttpFilter[Req, Resp, F] = new HttpFilter[Req, Resp, F] { override protected def backend: HttpBackend[Req, Resp, F] = baseBackend override def apply(request: Req, context: HttpContext[Req, Resp, F]): F[Resp] = { backend.rescue { body(request, context) } } } // Create a new default filter just for processing preceding filters def defaultFilter[Req, Resp, F[_]](backend: HttpBackend[Req, Resp, F]) = new SafeFilter(backend) private class AndThen[Req, Resp, F[_]]( protected val backend: HttpBackend[Req, Resp, F], prev: HttpFilter[Req, Resp, F], next: HttpFilter[Req, Resp, F] ) extends HttpFilter[Req, Resp, F] { override def apply(request: Req, context: HttpContext[Req, Resp, F]): F[Resp] = { backend.rescue { prev.apply(request, next.andThen(context)) } } } private[http] class SafeFilter[Req, Resp, F[_]](protected val backend: HttpBackend[Req, Resp, F]) extends HttpFilter[Req, Resp, F] { override def apply(request: Req, context: HttpContext[Req, Resp, F]): F[Resp] = { backend.rescue { context(request) } } } }
Example 72
Source File: HttpBackend.scala From airframe with Apache License 2.0 | 5 votes |
package wvlet.airframe.http import scala.concurrent.ExecutionContext import scala.language.higherKinds import scala.util.control.NonFatal trait HttpBackend[Req, Resp, F[_]] { self => type Filter = HttpFilter[Req, Resp, F] type Context = HttpContext[Req, Resp, F] protected implicit val httpRequestAdapter: HttpRequestAdapter[Req] def newResponse(status: HttpStatus, content: String = ""): Resp def toFuture[A](a: A): F[A] // Convert Scala's Future into the this backend's Future def toFuture[A](a: scala.concurrent.Future[A], e: ExecutionContext): F[A] def toScalaFuture[A](a: F[A]): scala.concurrent.Future[A] def wrapException(e: Throwable): F[Resp] def rescue(body: => F[Resp]): F[Resp] = { try { body } catch { case NonFatal(e) => wrapException(e) } } def isFutureType(x: Class[_]): Boolean def isScalaFutureType(x: Class[_]): Boolean = { classOf[scala.concurrent.Future[_]].isAssignableFrom(x) } // Returns true if the given class is the natively supported response type in this backend def isRawResponseType(x: Class[_]): Boolean // Map Future[A] into Future[B] def mapF[A, B](f: F[A], body: A => B): F[B] // Create a new Filter for this backend def newFilter(body: (Req, HttpContext[Req, Resp, F]) => F[Resp]): Filter = { HttpFilter.newFilter[Req, Resp, F](self, body) } // Create a new default filter just for processing preceding filters def defaultFilter: Filter = HttpFilter.defaultFilter(self) // Create a new default context that process the given request def newContext(body: Req => F[Resp]): Context = HttpContext.newContext[Req, Resp, F](self, body) // Prepare a thread-local holder for passing parameter values def withThreadLocalStore(request: => F[Resp]): F[Resp] // Set a thread-local context parameter value def setThreadLocal[A](key: String, value: A): Unit // Get a thread-local context parameter def getThreadLocal[A](key: String): Option[A] } object HttpBackend { // Pre-defined keys for the thread-local storage private[http] val TLS_KEY_RPC = "rpc" private[http] val TLS_KEY_SERVER_EXCEPTION = "server_exception" }
Example 73
Source File: HigherKindTypeTest.scala From airframe with Apache License 2.0 | 5 votes |
package wvlet.airframe import wvlet.airspec.AirSpec import scala.language.higherKinds object HigherKindTypeTest { trait Holder[M[_]] { def hello = "hello" } trait Task[A] trait MyFuture[A] trait HolderInterpreted extends Holder[Task] val interpreted = new HolderInterpreted { override def hello: String = "new interpretation" } val interpreted2 = new Holder[Task] { override def hello: String = "another interpretation" } val interpreted3 = new Holder[MyFuture] { override def hello: String = "third interpretation" } } import HigherKindTypeTest._ class HigherKindTypeTest extends AirSpec { scalaJsSupport val d = newSilentDesign .bind[HolderInterpreted].toInstance(interpreted) .bind[Holder[Task]].toInstance(interpreted2) .bind[Holder[MyFuture]].toInstance(interpreted3) def `support higher kind types`: Unit = { d.build[HolderInterpreted] { repo => repo.hello shouldBe "new interpretation" } d.build[Holder[Task]] { repo => repo.hello shouldBe "another interpretation" } d.build[Holder[MyFuture]] { repo => repo.hello shouldBe "third interpretation" } } }
Example 74
Source File: HigherKindedTypeBindingTest.scala From airframe with Apache License 2.0 | 5 votes |
package wvlet.airframe import wvlet.airframe.surface.Surface import wvlet.airspec.AirSpec import scala.concurrent.Future import scala.language.higherKinds import scala.util.Success object TaglessFinalExample { trait Wrapper[F[_]] { def wrap[A](v: A): F[A] } class WebApp[F[_]](implicit w: Wrapper[F]) { def serverInfo: F[String] = w.wrap("hello") } implicit object FutureWrapper extends Wrapper[Future] { override def wrap[A](v: A): Future[A] = Future.successful(v) } implicit object OptionWrapper extends Wrapper[Option] { override def wrap[A](v: A): Option[A] = Option(v) } def webAppWithFuture = new WebApp[Future] def webAppWithOption = new WebApp[Option] } class HigherKindedTypeBindingTest extends AirSpec { import TaglessFinalExample._ def `support higher-kinded type binding`: Unit = { warn("TODO: This currently works only for JVM. Need to fix SurfaceMacros for Scala.js") val s = Surface.of[WebApp[Future]] debug(s) debug(s.typeArgs(0)) val d = newDesign .bind[WebApp[Future]].toInstance(webAppWithFuture) .bind[WebApp[Option]].toInstance(webAppWithOption) .noLifeCycleLogging d.build[WebApp[Future]] { app => app.serverInfo.value shouldBe Some(Success("hello")) } d.build[WebApp[Option]] { app => app.serverInfo shouldBe Some("hello") } } }
Example 75
Source File: NamedParameterTest.scala From airframe with Apache License 2.0 | 5 votes |
package wvlet.airframe.surface.reflect import wvlet.airspec.AirSpec import scala.concurrent.Future import scala.language.higherKinds object NamedParameterTest extends AirSpec { trait MyService[F[_]] { def hello: F[String] } test("read F[_]") { val cl = classOf[MyService[Future]] val s = ReflectSurfaceFactory.ofClass(cl) s.toString shouldBe "MyService[F]" val m = ReflectSurfaceFactory.methodsOfClass(cl) m.headOption shouldBe defined val m1 = m.head m1.returnType.toString shouldBe "F[String]" } }
Example 76
Source File: RecursiveHigherKindTypeTest.scala From airframe with Apache License 2.0 | 5 votes |
package wvlet.airframe.surface import scala.language.higherKinds object RecursiveHigherKindTypeTest { trait Holder[M[_]] class MyTask[A] object Holder { type BySkinny[A] = MyTask[A] def bySkinny: Holder[BySkinny] = new InterpretedHolder } import Holder._ class InterpretedHolder extends Holder[BySkinny] {} } class RecursiveHigherKindTypeTest extends SurfaceSpec { scalaJsSupport import RecursiveHigherKindTypeTest._ import Holder.BySkinny def `support recursive higher kind types`: Unit = { val s = Surface.of[Holder[BySkinny]] s.name shouldBe "Holder[BySkinny]" s.typeArgs(0).dealias.name shouldBe "MyTask[A]" s.isAlias shouldBe false s.isPrimitive shouldBe false s.isOption shouldBe false s.dealias.toString shouldBe "Holder[BySkinny]" } }
Example 77
Source File: ETransform.scala From Scala-for-Machine-Learning-Second-Edition with MIT License | 5 votes |
package org.scalaml.core import org.scalaml.core.Design.Config import scala.language.higherKinds import scala.util.Try private[scalaml] abstract class ETransform[T, A](val config: Config) extends ITransform[T, A] { self => override def map[B](f: A => B): ETransform[T, B] = new ETransform[T, B](config) { override def |> : PartialFunction[T, Try[B]] = ??? } def flatMap[B](f: A => ETransform[T, B]): ETransform[T, B] = new ETransform[T, B](config) { override def |> : PartialFunction[T, Try[B]] = ??? } def compose[B](tr: ETransform[A, B]): ETransform[T, B] = new ETransform[T, B](config) { override def |> : PartialFunction[T, Try[B]] = ??? } } // ------------------------------- EOF -----------------------------------
Example 78
Source File: ITransform.scala From Scala-for-Machine-Learning-Second-Edition with MIT License | 5 votes |
package org.scalaml.core import scala.language.higherKinds import scala.util.Try def flatMap[B](f: A => ITransform[T, B]): ITransform[T, B] = new ITransform[T, B] { override def |> : PartialFunction[T, Try[B]] = new PartialFunction[T, Try[B]] { override def isDefinedAt(t: T): Boolean = self.|>.isDefinedAt(t) override def apply(t: T): Try[B] = self.|>(t).flatMap(f(_).|>(t)) } } def compose[B](tr: ITransform[A, B]): ITransform[T, B] = new ITransform[T, B] { override def |> : PartialFunction[T, Try[B]] = new PartialFunction[T, Try[B]] { override def isDefinedAt(t: T): Boolean = self.|>.isDefinedAt(t) && tr.|>.isDefinedAt(self.|>(t).get) override def apply(t: T): Try[B] = tr.|>(self.|>(t).get) } } } // ------------------------------- EOF -----------------------------------
Example 79
Source File: Boat.scala From Learn-Scala-Programming with MIT License | 5 votes |
package ch09 final case class Boat(direction: Double, position: (Double, Double)) { def go(speed: Float, time: Float): Boat = { val distance = speed * time val (x, y) = position val nx = x + distance * Math.cos(direction) val ny = y + distance * Math.sin(direction) copy(direction, (nx, ny)) } def turn(angle: Double): Boat = copy(direction = (this.direction + angle) % (2 * Math.PI)) } import scala.language.{higherKinds, implicitConversions} object Boat { val boat = Boat(0, (0d, 0d)) import Monad.lowPriorityImplicits._ def go[M[_]: Monad]: (Float, Float) => Boat => M[Boat] = (speed, time) => boat => Monad[M].unit(boat.go(speed, time)) def turn[M[_]: Monad]: Double => Boat => M[Boat] = angle => boat => Monad[M].unit(boat.turn(angle)) def move[A, M[_]: Monad](go: (Float, Float) => A => M[A], turn: Double => A => M[A])(boat: M[A]): M[A] = for { a <- boat b <- go(10,5)(a) c <- turn(0.5)(b) d <- go(20, 20)(c) e <- turn(-0.1)(d) f <- go(1,1)(e) } yield f }
Example 80
Source File: MonadSpecification.scala From Learn-Scala-Programming with MIT License | 5 votes |
package ch09 import ch09.Monad.Id import org.scalacheck._ import Prop._ import scala.language.higherKinds import scala.util.Try object MonadSpecification extends Properties("Monad") { def associativity[A, B, C, M[_]](implicit M: Monad[M], arbMA: Arbitrary[M[A]], arbMB: Arbitrary[M[B]], arbMC: Arbitrary[M[C]], arbB: Arbitrary[B], arbC: Arbitrary[C], cogenA: Cogen[A], cogenB: Cogen[B]): Prop = { forAll((as: M[A], f: A => M[B], g: B => M[C]) => { val leftSide = M.flatMap(M.flatMap(as)(f))(g) val rightSide = M.flatMap(as)(a => M.flatMap(f(a))(g)) leftSide == rightSide }) } def id[A, B, M[_]](implicit M: Monad[M], arbFA: Arbitrary[M[A]], arbFB: Arbitrary[M[B]], arbA: Arbitrary[A], cogenA: Cogen[A]): Prop = { val leftIdentity = forAll { as: M[A] => M.flatMap(as)(M.unit(_)) == as } val rightIdentity = forAll { (a: A, f: A => M[B]) => M.flatMap(M.unit(a))(f) == f(a) } leftIdentity && rightIdentity } def monad[A, B, C, M[_]](implicit M: Monad[M], arbMA: Arbitrary[M[A]], arbMB: Arbitrary[M[B]], arbMC: Arbitrary[M[C]], arbA: Arbitrary[A], arbB: Arbitrary[B], arbC: Arbitrary[C], cogenA: Cogen[A], cogenB: Cogen[B]): Prop = { id[A, B, M] && associativity[A, B, C, M] } property("Monad[Id] and Int => String, String => Long") = { monad[Int, String, Long, Id] } property("Monad[Id] and String => Int, Int => Boolean") = { monad[String, Int, Boolean, Id] } property("Monad[Option] and Int => String, String => Long") = { monad[Int, String, Long, Option] } property("Monad[Option] and String => Int, Int => Boolean") = { monad[String, Int, Boolean, Option] } type UnitEither[R] = Either[Unit, R] property("Monad[UnitEither[Int]] and Int => String, String => Long") = { monad[Int, String, Long, UnitEither] } property("Monad[UnitEither[String]] and String => Int, Int => Boolean") = { monad[String, Int, Boolean, UnitEither] } property("Monad[Try] and Int => String, String => Long") = { monad[Int, String, Long, Try] } property("Monad[Try] and String => Int, Int => Boolean") = { monad[String, Int, Boolean, Try] } property("Monad[List] and Int => String, String => Long") = { monad[Int, String, Long, List] } property("Monad[List] and String => Int, Int => Boolean") = { monad[String, Int, Boolean, List] } }
Example 81
Source File: Functor.scala From Learn-Scala-Programming with MIT License | 5 votes |
package ch08 import scala.language.{higherKinds, reflectiveCalls} import scala.util.Try trait Functor[F[_]] { def map[A,B](in: F[A])(f: A => B): F[B] def mapC[A,B](f: A => B): F[A] => F[B] = fa => map(fa)(f) } object Functor { implicit val bucketFunctor: Functor[List] = new Functor[List] { override def map[A, B](in: List[A])(f: A => B): List[B] = in.map(f) override def mapC[A, B](f: A => B): List[A] => List[B] = (_: List[A]).map(f) } implicit val optionFunctor: Functor[Option] = new Functor[Option] { override def map[A, B](in: Option[A])(f: A => B): Option[B] = in.map(f) override def mapC[A, B](f: A => B): Option[A] => Option[B] = (_: Option[A]).map(f) } implicit def eitherFunctor[L] = new Functor[({ type T[A] = Either[L, A] })#T] { override def map[A, B](in: Either[L, A])(f: A => B): Either[L, B] = in.map(f) override def mapC[A, B](f: A => B): Either[L, A] => Either[L, B] = (_: Either[L, A]).map(f) } implicit val tryFunctor: Functor[Try] = new Functor[Try] { override def map[A, B](in: Try[A])(f: A => B): Try[B] = in.map(f) override def mapC[A, B](f: A => B): Try[A] => Try[B] = (_: Try[A]).map(f) } }
Example 82
Source File: Applicative.scala From Learn-Scala-Programming with MIT License | 5 votes |
package ch08 import scala.language.{higherKinds, reflectiveCalls} import scala.util.{Failure, Success, Try} trait Applicative[F[_]] extends Functor[F] { def apply[A,B](a: F[A])(f: F[A => B]): F[B] def unit[A](a: => A): F[A] override def map[A,B](fa: F[A])(f: A => B): F[B] = apply(fa)(unit(f)) def map2[A,B,C](fa: F[A], fb: F[B])(f: (A, B) => C): F[C] = apply(fb)(map(fa)(f.curried)) def map3[A,B,C,D](fa: F[A], fb: F[B], fc: F[C])(f: (A, B, C) => D): F[D] = apply(fc)(apply(fb)(apply(fa)(unit(f.curried)))) def map4[A,B,C,D,E](fa: F[A], fb: F[B], fc: F[C], fd: F[D])(f: (A, B, C, D) => E): F[E] = { val ff: (A, B, C) => D => E = (a,b,c) => d => f(a,b,c,d) apply(fd)(map3(fa, fb, fc)(ff)) } def product[G[_]](G: Applicative[G]): Applicative[({type f[x] = (F[x], G[x])})#f] = { val F = this new Applicative[({type f[x] = (F[x], G[x])})#f] { def unit[A](a: => A) = (F.unit(a), G.unit(a)) override def apply[A,B](p: (F[A], G[A]))(fs: (F[A => B], G[A => B])) = (F.apply(p._1)(fs._1), G.apply(p._2)(fs._2)) } } def compose[G[_]](G: Applicative[G]): Applicative[({type f[x] = F[G[x]]})#f] = { val F = this def fab[A, B]: G[A => B] => G[A] => G[B] = (gf: G[A => B]) => (ga: G[A]) => G.apply(ga)(gf) def fg[B, A](f: F[G[A => B]]): F[G[A] => G[B]] = F.map(f)(fab) new Applicative[({type f[x] = F[G[x]]})#f] { def unit[A](a: => A) = F.unit(G.unit(a)) override def apply[A, B](a: F[G[A]])(f: F[G[A => B]]): F[G[B]] = F.apply(a)(fg(f)) } } } object Applicative { implicit val bucketApplicative: Applicative[List] = new Applicative[List] { override def apply[A, B](a: List[A])(f: List[A => B]): List[B] = (a, f) match { case (Nil, _) => Nil case (_, Nil) => Nil case (aa :: as, ff :: fs) => val fab: (A => B) => B = f => f(aa) ff(aa) :: as.map(ff) ::: fs.map(fab) ::: apply(as)(fs) case other => Nil } override def unit[A](a: => A): List[A] = List(a) } implicit val optionApplicative: Applicative[Option] = new Applicative[Option] { override def apply[A, B](a: Option[A])(f: Option[A => B]): Option[B] = (a,f) match { case (Some(a), Some(f)) => Some(f(a)) case _ => None } override def unit[A](a: => A): Option[A] = Some(a) } implicit def eitherApplicative[L] = new Applicative[({ type T[A] = Either[L, A] })#T] { override def apply[A, B](a: Either[L, A])(f: Either[L, A => B]): Either[L, B] = (a, f) match { case (Right(a), Right(f)) => Right(f(a)) case (Left(l), _) => Left(l) case (_, Left(l)) => Left(l) } override def unit[A](a: => A): Either[L, A] = Right(a) } implicit val tryApplicative: Applicative[Try] = new Applicative[Try] { override def apply[A, B](a: Try[A])(f: Try[A => B]): Try[B] = (a, f) match { case (Success(a), Success(f)) => Try(f(a)) case (Failure(ex), _) => Failure(ex) case (_, Failure(ex)) => Failure(ex) } override def unit[A](a: => A): Try[A] = Success(a) } }
Example 83
Source File: Traversable.scala From Learn-Scala-Programming with MIT License | 5 votes |
package ch08 import ch08.Model.Bucket import scala.language.{higherKinds, reflectiveCalls} import scala.util.{Failure, Success, Try} import scala.{Traversable => _} trait Traversable[F[_]] extends Functor[F] { def traverse[A,B,G[_]: Applicative](a: F[A])(f: A => G[B]): G[F[B]] def sequence[A,G[_]: Applicative](a: F[G[A]]): G[F[A]] = traverse(a)(identity) implicit def compose[H[_]](implicit H: Traversable[H]): Traversable[({type f[x] = F[H[x]]})#f] = { val F = this new Traversable[({type f[x] = F[H[x]]})#f] { override def traverse[A, B, G[_] : Applicative](fa: F[H[A]])(f: A => G[B]) = F.traverse(fa)((ga: H[A]) => H.traverse(ga)(f)) override def map[A, B](in: F[H[A]])(f: A => B): F[H[B]] = F.map(in)((ga: H[A]) => H.map(ga)(f)) } } } object Traversable { implicit val bucketTraversable = new Traversable[Bucket] { override def map[A, B](in: Bucket[A])(f: A => B): Bucket[B] = Functor.bucketFunctor.map(in)(f) override def traverse[A, B, G[_] : Applicative](a: Bucket[A])(f: A => G[B]): G[Bucket[B]] = { val G = implicitly[Applicative[G]] a.foldRight(G.unit(List[B]()))((aa, fbs) => G.map2(f(aa), fbs)(_ :: _)) } } implicit val optionTraversable = new Traversable[Option] { override def map[A, B](in: Option[A])(f: A => B): Option[B] = Functor.optionFunctor.map(in)(f) override def traverse[A, B, G[_] : Applicative](a: Option[A])(f: A => G[B]): G[Option[B]] = { val G = implicitly[Applicative[G]] a match { case Some(s) => G.map(f(s))(Some.apply) case None => G.unit(None) } } } implicit val tryTraversable = new Traversable[Try] { override def map[A, B](in: Try[A])(f: A => B): Try[B] = Functor.tryFunctor.map(in)(f) override def traverse[A, B, G[_] : Applicative](a: Try[A])(f: A => G[B]): G[Try[B]] = { val G = implicitly[Applicative[G]] a match { case Success(s) => G.map(f(s))(Success.apply) case Failure(ex) => G.unit(Failure(ex)) // re-wrap the ex to change the type of Failure } } } implicit def eitherTraversable[L] = new Traversable[({ type T[A] = Either[L, A] })#T] { override def map[A, B](in: Either[L, A])(f: A => B): Either[L, B] = Functor.eitherFunctor[L].map(in)(f) override def traverse[A, B, G[_] : Applicative](a: Either[L, A])(f: A => G[B]): G[Either[L, B]] = { val G = implicitly[Applicative[G]] a match { case Right(s) => G.map(f(s))(Right.apply) case Left(l) => G.unit(Left(l)) // re-wrap the l to change the type of Failure } } } }
Example 84
Source File: FunctorSpecification.scala From Learn-Scala-Programming with MIT License | 5 votes |
package ch08 import org.scalacheck._ import org.scalacheck.Prop._ import scala.language.higherKinds import scala.util.Try object FunctorSpecification extends Properties("Functor") { def id[A, F[_]](implicit F: Functor[F], arbFA: Arbitrary[F[A]]): Prop = forAll { as: F[A] => F.map(as)(identity) == as } def associativity[A, B, C, F[_]](implicit F: Functor[F], arbFA: Arbitrary[F[A]], arbB: Arbitrary[B], arbC: Arbitrary[C], cogenA: Cogen[A], cogenB: Cogen[B]): Prop = { forAll((as: F[A], f: A => B, g: B => C) => { F.map(F.map(as)(f))(g) == F.map(as)(f andThen g) }) } def functor[A, B, C, F[_]](implicit F: Functor[F], arbFA: Arbitrary[F[A]], arbB: Arbitrary[B], arbC: Arbitrary[C], cogenA: Cogen[A], cogenB: Cogen[B]): Prop = id[A, F] && associativity[A, B, C, F] import Functor._ property("Functor[Option] and Int => String, String => Long") = { functor[Int, String, Long, Option] } property("Functor[Option] and String => Int, Int => Boolean") = { functor[String, Int, Boolean, Option] } type UnitEither[R] = Either[Unit, R] property("Functor[Either] and Int => String, String => Long") = { functor[Int, String, Long, UnitEither] } property("Functor[Either] and String => Int, Int => Boolean") = { functor[String, Int, Boolean, UnitEither] } property("Functor[Try] and Int => String, String => Long") = { functor[Int, String, Long, Try] } property("Functor[Try] and String => Int, Int => Boolean") = { functor[String, Int, Boolean, Try] } }
Example 85
Source File: FreeMonad.scala From Learn-Scala-Programming with MIT License | 5 votes |
package ch10 import ch08.Functor import scala.annotation.tailrec import scala.language.higherKinds object FreeMonad extends App { case class Bait(name: String) extends AnyVal case class Line(length: Int) extends AnyVal case class Fish(name: String) extends AnyVal sealed trait Action[A] final case class BuyBait[A](name: String, f: Bait => A) extends Action[A] final case class CastLine[A](bait: Bait, f: Line => A) extends Action[A] final case class HookFish[A](line: Line, f: Fish => A) extends Action[A] // assessment final case class ReleaseFish[A](fish: Fish, f: Unit => A) extends Action[A] final case class Done[F[_]: Functor, A](a: A) extends Free[F, A] final case class Join[F[_]: Functor, A](action: F[Free[F, A]]) extends Free[F, A] class Free[F[_]: Functor, A] { def flatMap[B](f: A => Free[F, B]): Free[F, B] = this match { case Done(a) => f(a) case Join(a) => Join(implicitly[Functor[F]].map(a)(_.flatMap(f))) } def map[B](f: A => B): Free[F, B] = flatMap(a => Done(f(a))) } implicit lazy val actionFunctor: Functor[Action] = new Functor[Action] { override def map[A, B](in: Action[A])(f: A => B): Action[B] = in match { case BuyBait(name, a) => BuyBait(name, x => f(a(x))) case CastLine(bait, a) => CastLine(bait, x => f(a(x))) case HookFish(line, a) => HookFish(line, x => f(a(x))) // assessment case ReleaseFish(fish, a) => ReleaseFish(fish, x => f(a(x))) } } def buyBait(name: String): Free[Action, Bait] = Join(BuyBait(name, bait => Done(bait))) def castLine(bait: Bait): Free[Action, Line] = Join(CastLine(bait, line => Done(line))) def hookFish(line: Line): Free[Action, Fish] = Join(HookFish(line, fish => Done(fish))) // assessment def releaseFish(fish: Fish): Free[Action, Unit] = Join(ReleaseFish(fish, _ => Done(()))) def catchFish(baitName: String): Free[Action, _] = for { bait <- buyBait(baitName) line <- castLine(bait) fish <- hookFish(line) _ <- releaseFish(fish) } yield () def log[A](a: A): Unit = println(a) @tailrec def goFishingLogging[A](actions: Free[Action, A], unit: Unit): A = actions match { case Join(BuyBait(name, f)) => goFishingLogging(f(Bait(name)), log(s"Buying bait $name")) case Join(CastLine(bait, f)) => goFishingLogging(f(Line(bait.name.length)), log(s"Casting line with ${bait.name}")) case Join(HookFish(line, f)) => goFishingLogging(f(Fish("CatFish")), log(s"Hooking fish from ${line.length} feet")) case Done(fish) => fish // assessment case Join(ReleaseFish(fish, f)) => goFishingLogging(f(()), log(s"Releasing the fish $fish")) } println(goFishingLogging(catchFish("Crankbait"), ())) @tailrec def goFishingAcc[A](actions: Free[Action, A], log: List[AnyVal]): List[AnyVal] = actions match { case Join(BuyBait(name, f)) => val bait = Bait(name) goFishingAcc(f(bait), bait :: log) case Join(CastLine(bait, f)) => val line = Line(bait.name.length) goFishingAcc(f(line), line :: log) case Join(HookFish(line, f)) => val fish = Fish(s"CatFish from ($line)") goFishingAcc(f(fish), fish :: log) case Done(_) => log.reverse // assessment case Join(ReleaseFish(fish, f)) => goFishingAcc(f(()), fish.copy(name = fish.name + " released") :: log) } lazy val log = goFishingAcc(catchFish("Crankbait"), Nil) println(log) }
Example 86
Source File: InfixTypes.scala From Learn-Scala-Programming with MIT License | 5 votes |
package ch02 object InfixTypes { import Linearization._ import scala.language.higherKinds type Or[A, B] type And[A, B] type +=[A, B] = Or[A, B] type =:[A, B] = And[A, B] type CC = Or[And[A, B], C] type DA = A =: B =: C type DB = A And B And C // type E = A += B =: C // wrong associativity type F = (A += B) =: C type |[A, B] = Or[A, B] type &[A, B] = And[A, B] type G = A & B | C }
Example 87
Source File: MonoidFoldable.scala From Learn-Scala-Programming with MIT License | 5 votes |
package ch07 import scala.concurrent.{ExecutionContext, Future} import scala.language.higherKinds trait MonoidFoldable[A, F[_]] { def foldRight(as: F[A]): A def foldLeft(as: F[A]): A def foldBalanced(as: F[A]): A def foldPar(as: F[A])(implicit ec: ExecutionContext): Future[A] } object MonoidFoldable { implicit def listMonoidFoldable[A : Monoid]: MonoidFoldable[A, List] = new MonoidFoldable[A, List] { private val m = implicitly[Monoid[A]] override def foldRight(as: List[A]): A = as.foldRight(m.identity)(m.op) override def foldLeft(as: List[A]): A = as.foldLeft(m.identity)(m.op) override def foldBalanced(as: List[A]): A = as match { case Nil => m.identity case List(one) => one case _ => val (l, r) = as.splitAt(as.length/2) m.op(foldBalanced(l), foldBalanced(r)) } private val parallelLimit = 10 override def foldPar(as: List[A])(implicit ec: ExecutionContext): Future[A] = { if (as.length < parallelLimit) Future(foldBalanced(as)) else { val (l, r) = as.splitAt(as.length/2) Future.reduceLeft(List(foldPar(l), foldPar(r)))(m.op) } } } }
Example 88
Source File: Assessment.scala From Learn-Scala-Programming with MIT License | 5 votes |
package ch07 import scala.language.higherKinds import scala.language.reflectiveCalls import scala.util._ object Assessment { implicit val booleanOr: Monoid[Boolean] = new Monoid[Boolean] { override def identity: Boolean = false override def op(l: Boolean, r: Boolean): Boolean = l || r } implicit val booleanAnd: Monoid[Boolean] = new Monoid[Boolean] { override def identity: Boolean = true override def op(l: Boolean, r: Boolean): Boolean = l && r } implicit def option[A : Monoid]: Monoid[Option[A]] = new Monoid[Option[A]] { override def identity: Option[A] = None override def op(l: Option[A], r: Option[A]): Option[A] = (l, r) match { case (Some(la), Some(lb)) => Option(implicitly[Monoid[A]].op(la, lb)) case _ => l orElse r } } def either[L, R : Monoid]: Monoid[Either[L, R]] = new Monoid[Either[L, R]] { private val ma = implicitly[Monoid[R]] override def identity: Either[L, R] = Right(ma.identity) override def op(l: Either[L, R], r: Either[L, R]): Either[L, R] = (l, r) match { case (l @ Left(_), _) => l case (_, l @ Left(_)) => l case (Right(la), Right(lb)) => Right(ma.op(la, lb)) } } }
Example 89
Source File: StrictOptimizedSeqOps.scala From perf_tester with Apache License 2.0 | 5 votes |
package scala package collection package immutable import scala.language.higherKinds trait StrictOptimizedSeqOps[+A, +CC[_], +C] extends SeqOps[A, CC, C] with collection.StrictOptimizedSeqOps[A, CC, C] { override def updated[B >: A](index: Int, elem: B): CC[B] = { if (index < 0) throw new IndexOutOfBoundsException(index.toString) val b = iterableFactory.newBuilder[B]() if (knownSize >= 0) { b.sizeHint(size) } var i = 0 val it = iterator() while (i < index && it.hasNext) { b += it.next() i += 1 } if (!it.hasNext) throw new IndexOutOfBoundsException(index.toString) b += elem it.next() while (it.hasNext) b += it.next() b.result() } override def patch[B >: A](from: Int, other: IterableOnce[B], replaced: Int): CC[B] = { val b = iterableFactory.newBuilder[B]() var i = 0 val it = iterator() while (i < from && it.hasNext) { b += it.next() i += 1 } b ++= other i = replaced while (i > 0 && it.hasNext) { it.next() i -= 1 } while (it.hasNext) b += it.next() b.result() } }
Example 90
Source File: StrictOptimizedSortedSetOps.scala From perf_tester with Apache License 2.0 | 5 votes |
package scala package collection import scala.annotation.unchecked.uncheckedVariance import scala.language.higherKinds trait StrictOptimizedSortedSetOps[A, +CC[X] <: SortedSet[X], +C <: SortedSetOps[A, CC, C]] extends SortedSetOps[A, CC, C] with StrictOptimizedIterableOps[A, Set, C] { override def map[B : Ordering](f: A => B): CC[B] = { val b = sortedIterableFactory.newBuilder[B]() val it = iterator() while (it.hasNext) { b += f(it.next()) } b.result() } override def flatMap[B : Ordering](f: A => IterableOnce[B]): CC[B] = { val b = sortedIterableFactory.newBuilder[B]() val it = iterator() while (it.hasNext) { b ++= f(it.next()) } b.result() } override def zip[B](that: Iterable[B])(implicit ev: Ordering[(A @uncheckedVariance, B)]): CC[(A @uncheckedVariance, B)] = { // sound bcs of VarianceNot val b = sortedIterableFactory.newBuilder[(A, B)]() val it1 = iterator() val it2 = that.iterator() while (it1.hasNext && it2.hasNext) { b += ((it1.next(), it2.next())) } b.result() } override def collect[B : Ordering](pf: PartialFunction[A, B]): CC[B] = { val b = sortedIterableFactory.newBuilder[B]() val it = iterator() while (it.hasNext) { val elem = it.next() if (pf.isDefinedAt(elem)) { b += pf.apply(elem) } } b.result() } }
Example 91
Source File: IsSeqLike.scala From perf_tester with Apache License 2.0 | 5 votes |
package scala.collection package generic val conversion: Repr => SeqOps[A, Seq, Repr] } object IsSeqLike { import scala.language.higherKinds implicit val stringRepr: IsSeqLike[String] { type A = Char } = new IsSeqLike[String] { type A = Char val conversion = implicitly[String => SeqOps[Char, Seq, String]] } implicit def SeqRepr[C[X] <: Seq[X], A0](implicit conv: C[A0] => SeqOps[A0, C, C[A0]]): IsSeqLike[C[A0]] { type A = A0 } = new IsSeqLike[C[A0]] { type A = A0 val conversion = conv } }
Example 92
Source File: StrictOptimizedSeqOps.scala From perf_tester with Apache License 2.0 | 5 votes |
package scala.collection import scala.language.higherKinds trait StrictOptimizedSeqOps [+A, +CC[_], +C] extends Any with SeqOps[A, CC, C] with StrictOptimizedIterableOps[A, CC, C] { override def distinctBy[B](f: A => B): C = { val builder = newSpecificBuilder() val seen = mutable.HashSet.empty[B] for (x <- this) { val y = f(x) if (!seen.contains(y)) { seen += y builder += x } } builder.result() } override def prepended[B >: A](elem: B): CC[B] = { val b = iterableFactory.newBuilder[B]() if (knownSize >= 0) { b.sizeHint(size + 1) } b += elem b ++= this b.result() } override def appended[B >: A](elem: B): CC[B] = { val b = iterableFactory.newBuilder[B]() if (knownSize >= 0) { b.sizeHint(size + 1) } b ++= this b += elem b.result() } override def appendedAll[B >: A](suffix: Iterable[B]): CC[B] = { val b = iterableFactory.newBuilder[B]() b ++= this b ++= suffix b.result() } override def prependedAll[B >: A](prefix: Iterable[B]): CC[B] = { val b = iterableFactory.newBuilder[B]() b ++= prefix b ++= this b.result() } override def padTo[B >: A](len: Int, elem: B): CC[B] = { val b = iterableFactory.newBuilder[B]() val L = size b.sizeHint(math.max(L, len)) var diff = len - L b ++= this while (diff > 0) { b += elem diff -= 1 } b.result() } }
Example 93
Source File: package.scala From perf_tester with Apache License 2.0 | 5 votes |
package scala import scala.language.higherKinds package object collection { @deprecated("Use Iterable instead of Traversable", "2.13.0") type Traversable[+X] = Iterable[X] @deprecated("Use Iterable instead of Traversable", "2.13.0") val Traversable = Iterable @deprecated("Use IterableOnce instead of TraversableOnce", "2.13.0") type TraversableOnce[+X] = IterableOnce[X] @deprecated("Use IterableOnce instead of TraversableOnce", "2.13.0") val TraversableOnce = IterableOnce @deprecated("Use SeqOps instead of SeqLike", "2.13.0") type SeqLike[A, T] = SeqOps[A, Seq, T] @deprecated("Use SeqOps (for the methods) or IndexedSeqOps (for fast indexed access) instead of ArrayLike", "2.13.0") type ArrayLike[A] = SeqOps[A, Seq, Seq[A]] @deprecated("Gen* collection types have been removed", "2.13.0") type GenTraversableOnce[+X] = IterableOnce[X] @deprecated("Gen* collection types have been removed", "2.13.0") val GenTraversableOnce = IterableOnce @deprecated("Gen* collection types have been removed", "2.13.0") type GenTraversable[+X] = Iterable[X] @deprecated("Gen* collection types have been removed", "2.13.0") val GenTraversable = Iterable @deprecated("Gen* collection types have been removed", "2.13.0") type GenIterable[+X] = Iterable[X] @deprecated("Gen* collection types have been removed", "2.13.0") val GenIterable = Iterable @deprecated("Gen* collection types have been removed", "2.13.0") type GenSeq[+X] = Seq[X] @deprecated("Gen* collection types have been removed", "2.13.0") val GenSeq = Seq @deprecated("Gen* collection types have been removed", "2.13.0") type GenSet[X] = Set[X] @deprecated("Gen* collection types have been removed", "2.13.0") val GenSet = Set @deprecated("Gen* collection types have been removed", "2.13.0") type GenMap[K, +V] = Map[K, V] @deprecated("Gen* collection types have been removed", "2.13.0") val GenMap = Map def unapply[A, CC[_] <: Seq[_], C <: SeqOps[A, CC, C]](t: C with SeqOps[A, CC, C]): Option[(C, A)] = if(t.isEmpty) None else Some(t.init -> t.last) } }
Example 94
Source File: TraceGenerators.scala From money with Apache License 2.0 | 5 votes |
package com.comcast.money.core import java.time.Instant import java.util.UUID import org.scalacheck.{ Arbitrary, Gen } import scala.concurrent.duration._ import scala.language.higherKinds import Arbitrary.arbitrary import com.comcast.money.api.{ Note, Span, SpanId } import org.scalacheck.Gen.{ alphaLowerChar, alphaUpperChar, choose, frequency } trait TraceGenerators { def genOption[A](g: Gen[A]): Gen[Option[A]] = Gen.oneOf(Gen.const(Option.empty[A]), g map Option.apply) def genUUID: Gen[UUID] = for { hi <- arbitrary[Long] lo <- arbitrary[Long] } yield new UUID(hi, lo) def genStr: Gen[String] = Gen.listOf(Gen.alphaNumChar) map { _.mkString } def genHexStrFromLong: Gen[String] = for { l <- arbitrary[Long] } yield l.toHexString def genTraceSystemMetadataPair: Gen[(String, String)] = for { name <- genStr value <- genStr } yield name -> value def genTraceSystemMetadata: Gen[Map[String, String]] = Gen.nonEmptyMap(genTraceSystemMetadataPair) def genSpanId: Gen[SpanId] = for { traceId <- genUUID parentId <- arbitrary[Long] childId <- arbitrary[Long] } yield new SpanId(traceId.toString, parentId, childId) }
Example 95
Source File: InternalSubscriberStub.scala From lagom with Apache License 2.0 | 5 votes |
package com.lightbend.lagom.internal.testkit import akka.Done import akka.actor.ActorRef import akka.stream.Materializer import akka.stream.OverflowStrategy import akka.stream.scaladsl.Flow import akka.stream.scaladsl.Keep import akka.stream.scaladsl.Sink import akka.stream.scaladsl.Source import scala.concurrent.Future import scala.language.higherKinds private[lagom] class InternalSubscriberStub[Payload, Message[_]]( groupId: String, topicBuffer: ActorRef )(implicit materializer: Materializer) { def mostOnceSource: Source[Message[Payload], _] = { Source .actorRef[Message[Payload]](1024, OverflowStrategy.fail) .prependMat(Source.empty)(subscribeToBuffer) } def leastOnce(flow: Flow[Message[Payload], Done, _]): Future[Done] = { mostOnceSource .via(flow) .toMat(Sink.ignore)(Keep.right[Any, Future[Done]]) .run() } private def subscribeToBuffer[R](ref: ActorRef, t: R) = { topicBuffer.tell(TopicBufferActor.SubscribeToBuffer(groupId, ref), ActorRef.noSender) t } }
Example 96
Source File: tests.scala From mercator with Apache License 2.0 | 5 votes |
package mercator.tests import mercator._ import scala.language.higherKinds object Tests { def main(args: Array[String]): Unit = { applicative[Option] monadic[({ type L[W] = Either[String, W] })#L] filterable[Seq] def increment[F[_]: Monadic](xs: F[Int]) = for(x <- xs) yield x + 1 increment(List(1, 2, 3)) increment(Option(4)) increment(Iterable(5)) increment[({ type L[W] = Either[String, W] })#L](Left("")) () } }
Example 97
Source File: mercator.scala From mercator with Apache License 2.0 | 5 votes |
package mercator import scala.language.higherKinds import scala.reflect.macros._ import scala.collection.generic.CanBuildFrom import language.experimental.macros import language.reflectiveCalls object `package` { implicit def monadic[F[_]]: Monadic[F] = macro Mercator.instantiate.monadic[F[Nothing]] final implicit class Ops[M[_], A](val value: M[A]) extends AnyVal { @inline def flatMap[B](fn: A => M[B])(implicit monadic: Monadic[M]): M[B] = monadic.flatMap[A, B](value)(fn) @inline def map[B](fn: A => B)(implicit functor: Functor[M]): M[B] = functor.map[A, B](value)(fn) @inline def filter(fn: A => Boolean)(implicit filterable: Filterable[M]): M[A] = filterable.filter[A](value)(fn) } implicit def functor[F[_]]: Functor[F] = macro Mercator.instantiate.functor[F[Nothing]] implicit def filterable[F[_]]: Filterable[F] = macro Mercator.instantiate.filterable[F[Nothing]] } object Mercator { object instantiate { def functor[F: c.WeakTypeTag](c: whitebox.Context): c.Tree = common(c).functor def monadic[F: c.WeakTypeTag](c: whitebox.Context): c.Tree = common(c).monadic def filterable[F: c.WeakTypeTag](c: whitebox.Context): c.Tree = common(c).filterable } def common[F: c.WeakTypeTag](c: whitebox.Context) = new { import c.universe._ private val typeConstructor = weakTypeOf[F].typeConstructor private val mockType = appliedType(typeConstructor, typeOf[Mercator.type]) private val companion = typeConstructor.dealias.typeSymbol.companion private val returnType = scala.util.Try(c.typecheck(q"$companion.apply(_root_.mercator.Mercator)").tpe) private def pointAp = if(returnType.map(_ <:< mockType).getOrElse(false)) q"${companion.asModule}(value)" else { val subtypes = typeConstructor.typeSymbol.asClass.knownDirectSubclasses.filter { sub => c.typecheck(q"${sub.companion}.apply(_root_.mercator.Mercator)").tpe <:< mockType }.map { sub => q"${sub.companion}.apply(value)" } if(subtypes.size == 1) subtypes.head else c.abort(c.enclosingPosition, s"mercator: unable to derive Monadic instance for type constructor $typeConstructor") } def monadic: c.Tree = q""" new _root_.mercator.Monadic[$typeConstructor] { def point[A](value: A): Apply[A] = ${pointAp} def map[A, B](from: Apply[A])(fn: A => B): Apply[B] = from.map(fn) def flatMap[A, B](from: Apply[A])(fn: A => Apply[B]): Apply[B] = from.flatMap(fn) } """ def functor: c.Tree = q""" new _root_.mercator.Functor[$typeConstructor] { def point[A](value: A): Apply[A] = ${pointAp} def map[A, B](from: Apply[A])(fn: A => B): Apply[B] = from.map(fn) } """ def filterable: c.Tree = q""" new _root_.mercator.Filterable[$typeConstructor] { def filter[A](value: Apply[A])(fn: A => Boolean): Apply[A] = value.filter(fn) } """ } } trait Functor[F[_]] { type Apply[X] = F[X] def point[A](value: A): F[A] def map[A, B](from: F[A])(fn: A => B): F[B] } trait Monadic[F[_]] extends Functor[F] { def flatMap[A, B](from: F[A])(fn: A => F[B]): F[B] } trait Filterable[F[_]] { type Apply[X] = F[X] def filter[A](value: F[A])(fn: A => Boolean): F[A] }
Example 98
Source File: Fs2SubscriptionStream.scala From sangria with Apache License 2.0 | 5 votes |
package sangria.util import cats.effect.{ContextShift, IO} import fs2.Stream import sangria.streaming.SubscriptionStream import scala.concurrent.Future import scala.language.higherKinds object Fs2Support { type IOS[A] = Stream[IO, A] class Fs2SubscriptionStream(implicit CS: ContextShift[IO]) extends SubscriptionStream[IOS] { def supported[T[_]](other: SubscriptionStream[T]) = other.isInstanceOf[Fs2SubscriptionStream] def map[A, B](source: IOS[A])(fn: A => B) = source.map(fn) def singleFuture[T](value: Future[T]) = Stream.eval(IO.fromFuture(IO(value))) def single[T](value: T) = Stream.emit(value) def mapFuture[A, B](source: IOS[A])(fn: A => Future[B]) = source.evalMap(a => IO.fromFuture(IO(fn(a)))) def first[T](s: IOS[T]) = s.compile.toVector.map(_.head).unsafeToFuture def failed[T](e: Throwable) = Stream.raiseError[IO](e) def onComplete[Ctx, Res](result: IOS[Res])(op: => Unit) = result.onFinalize(IO(op)) def flatMapFuture[Ctx, Res, T](future: Future[T])(resultFn: T => IOS[Res]) = Stream.eval(IO.fromFuture(IO(future))).flatMap(resultFn) def merge[T](streams: Vector[IOS[T]]) = if (streams.nonEmpty) streams.tail.foldLeft(streams.head)(_.merge(_)) else throw new IllegalStateException("No streams produced!") def recover[T](stream: IOS[T])(fn: Throwable => T) = stream.handleErrorWith { case e => Stream.emit(fn(e)) } } implicit def observableSubscriptionStream(implicit CS: ContextShift[IO]): SubscriptionStream[IOS] = new Fs2SubscriptionStream }
Example 99
Source File: CanBuildFromSrc.scala From scala-library-compat with Apache License 2.0 | 5 votes |
package fix import scala.language.higherKinds import scala.collection.immutable import scala.collection.immutable import scala.collection.compat._ object CanBuildFromSrc { def f[C0, A, C1[_]](c0: C0)(implicit cbf: Factory[Int, C1[Int]], cbf2: Factory[String, C1[String]], cbf3: BuildFrom[C0, A, C1[A]]): C1[Int] = { val b = cbf.newBuilder val b2 = cbf.newBuilder val b3 = cbf.newBuilder val b4 = cbf2.newBuilder val b5 = cbf3.newBuilder(c0) val b6 = cbf3.newBuilder(c0) cbf.fromSpecific(List.empty[Int]) cbf2.fromSpecific(List.empty[String]) b.result() } def kind(implicit cbf: BuildFrom[String, Char, String], cbf2: BuildFrom[String, (Int, Boolean), Map[Int, Boolean]]): Unit = { cbf.newBuilder("") cbf2.newBuilder("") () } def f2[T, That](implicit cbf: Factory[T, That]): Foo[T, That] = new Foo def f3[T, That](implicit cbf: Factory[T, That with immutable.Iterable[_]]): Foo[T, That] = new Foo class Foo[T, That](implicit cbf: Factory[T, That]) { val b = cbf.newBuilder } }
Example 100
Source File: CanBuildFromSrc.scala From scala-library-compat with Apache License 2.0 | 5 votes |
package fix import scala.language.higherKinds import scala.collection.immutable import collection.generic.CanBuildFrom object CanBuildFromSrc { def f[C0, A, C1[_]](c0: C0)(implicit cbf: CanBuildFrom[Nothing, Int, C1[Int]], cbf2: CanBuildFrom[Nothing, String, C1[String]], cbf3: CanBuildFrom[C0, A, C1[A]]): C1[Int] = { val b = cbf() val b2 = cbf.apply val b3 = cbf.apply() val b4 = cbf2.apply() val b5 = cbf3(c0) val b6 = cbf3.apply(c0) List.empty[Int].to[C1] List.empty[String].to[C1] b.result() } def kind(implicit cbf: CanBuildFrom[String, Char, String], cbf2: CanBuildFrom[String, (Int, Boolean), Map[Int, Boolean]]): Unit = { cbf("") cbf2("") () } def f2[T, That](implicit cbf: CanBuildFrom[Nothing, T, That]): Foo[T, That] = new Foo def f3[T, That](implicit cbf: CanBuildFrom[Nothing, T, That with immutable.Traversable[_]]): Foo[T, That] = new Foo class Foo[T, That](implicit cbf: CanBuildFrom[Nothing, T, That]) { val b = cbf() } }
Example 101
Source File: PubSubRequests.scala From scredis with Apache License 2.0 | 5 votes |
package scredis.protocol.requests import scredis.protocol._ import scredis.serialization.Writer import scala.collection.generic.CanBuildFrom import scala.language.higherKinds object PubSubRequests { import scredis.serialization.Implicits.{intReader, stringReader} object PSubscribe extends Command("PSUBSCRIBE") object Publish extends Command("PUBLISH") with WriteCommand object PubSubChannels extends Command("PUBSUB", "CHANNELS") object PubSubNumSub extends Command("PUBSUB", "NUMSUB") object PubSubNumPat extends ZeroArgCommand("PUBSUB", "NUMPAT") object PUnsubscribe extends Command("PUNSUBSCRIBE") object Subscribe extends Command("SUBSCRIBE") object Unsubscribe extends Command("UNSUBSCRIBE") case class PSubscribe(patterns: String*) extends Request[Int]( PSubscribe, patterns: _* ) { override def decode = ??? } case class Publish[W: Writer](channel: String, message: W) extends Request[Long]( Publish, channel, implicitly[Writer[W]].write(message) ) { override def decode = { case IntegerResponse(value) => value } } case class PubSubChannels(patternOpt: Option[String]) extends Request[List[String]](PubSubChannels, patternOpt.toSeq: _*) { override def decode = { case a: ArrayResponse => a.parsed[String, List] { case b: BulkStringResponse => b.flattened[String] } } } case class PubSubNumSub(channels: String*) extends Request[Map[String, Long]](PubSubNumSub, channels: _*) { override def decode = { case a: ArrayResponse => a.parsedAsPairsMap[String, Long, Map] { case b: BulkStringResponse => b.flattened[String] } { case IntegerResponse(value) => value } } } case class PubSubNumPat() extends Request[Long](PubSubNumPat) { override def decode = { case IntegerResponse(value) => value } } case class PUnsubscribe(patterns: String*) extends Request[Int]( PUnsubscribe, patterns: _* ) { override def decode = ??? } case class Subscribe(channels: String*) extends Request[Int]( Subscribe, channels: _* ) { override def decode = ??? } case class Unsubscribe(channels: String*) extends Request[Int]( Unsubscribe, channels: _* ) { override def decode = ??? } }
Example 102
Source File: package.scala From scredis with Apache License 2.0 | 5 votes |
package scredis.protocol import scala.collection.mutable.ListBuffer import scala.language.higherKinds package object requests { private[requests] def generateScanLikeArgs( keyOpt: Option[String], cursor: Long, matchOpt: Option[String], countOpt: Option[Int] ): List[Any] = { val args = ListBuffer[Any]() keyOpt.foreach { args += _ } args += cursor countOpt.foreach { args += "COUNT" += _ } matchOpt.foreach { args += "MATCH" += _ } args.toList } private[requests] def unpair[A, B, CC[X] <: Iterable[X]](pairs: CC[(A, B)]): List[Any] = { val unpaired = ListBuffer[Any]() pairs.foreach { case (a, b) => unpaired += a += b } unpaired.toList } }
Example 103
Source File: ToMappable.scala From shapeless-datatype with Apache License 2.0 | 5 votes |
package shapeless.datatype.mappable import shapeless._ import shapeless.labelled.FieldType import scala.language.higherKinds trait ToMappable[L <: HList, M] extends Serializable { def apply(l: L): M } trait LowPriorityToMappable1 { implicit def hconsToMappable1[K <: Symbol, V, T <: HList, M](implicit wit: Witness.Aux[K], mt: MappableType[M, V], toT: Lazy[ToMappable[T, M]] ): ToMappable[FieldType[K, V] :: T, M] = new ToMappable[FieldType[K, V] :: T, M] { override def apply(l: FieldType[K, V] :: T): M = mt.put(wit.value.name, l.head, toT.value(l.tail)) } } trait LowPriorityToMappableOption1 extends LowPriorityToMappable1 { implicit def hconsToMappableOption1[K <: Symbol, V, T <: HList, M](implicit wit: Witness.Aux[K], mt: MappableType[M, V], toT: Lazy[ToMappable[T, M]] ): ToMappable[FieldType[K, Option[V]] :: T, M] = new ToMappable[FieldType[K, Option[V]] :: T, M] { override def apply(l: FieldType[K, Option[V]] :: T): M = mt.put(wit.value.name, l.head, toT.value(l.tail)) } } trait LowPriorityToMappableSeq1 extends LowPriorityToMappableOption1 { implicit def hconsToMappableSeq1[K <: Symbol, V, T <: HList, M, S[_]](implicit wit: Witness.Aux[K], mt: MappableType[M, V], toT: Lazy[ToMappable[T, M]], toSeq: S[V] => Seq[V] ): ToMappable[FieldType[K, S[V]] :: T, M] = new ToMappable[FieldType[K, S[V]] :: T, M] { override def apply(l: FieldType[K, S[V]] :: T): M = mt.put(wit.value.name, toSeq(l.head), toT.value(l.tail)) } } trait LowPriorityToMappable0 extends LowPriorityToMappableSeq1 { implicit def hconsToMappable0[K <: Symbol, V, H <: HList, T <: HList, M: CanNest](implicit wit: Witness.Aux[K], gen: LabelledGeneric.Aux[V, H], mbt: BaseMappableType[M], toH: Lazy[ToMappable[H, M]], toT: Lazy[ToMappable[T, M]] ): ToMappable[FieldType[K, V] :: T, M] = new ToMappable[FieldType[K, V] :: T, M] { override def apply(l: FieldType[K, V] :: T): M = mbt.put(wit.value.name, toH.value(gen.to(l.head)), toT.value(l.tail)) } } trait LowPriorityToMappableOption0 extends LowPriorityToMappable0 { implicit def hconsToMappableOption0[K <: Symbol, V, H <: HList, T <: HList, M: CanNest](implicit wit: Witness.Aux[K], gen: LabelledGeneric.Aux[V, H], mbt: BaseMappableType[M], toH: Lazy[ToMappable[H, M]], toT: Lazy[ToMappable[T, M]] ): ToMappable[FieldType[K, Option[V]] :: T, M] = new ToMappable[FieldType[K, Option[V]] :: T, M] { override def apply(l: FieldType[K, Option[V]] :: T): M = mbt.put(wit.value.name, l.head.map(h => toH.value(gen.to(h))), toT.value(l.tail)) } } trait LowPriorityToMappableSeq0 extends LowPriorityToMappableOption0 { implicit def hconsToMappableSeq0[K <: Symbol, V, H <: HList, T <: HList, M: CanNest, S[_]]( implicit wit: Witness.Aux[K], gen: LabelledGeneric.Aux[V, H], mbt: BaseMappableType[M], toH: Lazy[ToMappable[H, M]], toT: Lazy[ToMappable[T, M]], toSeq: S[V] => Seq[V] ): ToMappable[FieldType[K, S[V]] :: T, M] = new ToMappable[FieldType[K, S[V]] :: T, M] { override def apply(l: FieldType[K, S[V]] :: T): M = mbt.put(wit.value.name, toSeq(l.head).map(h => toH.value(gen.to(h))), toT.value(l.tail)) } } object ToMappable extends LowPriorityToMappableSeq0 { implicit def hnilToMappable[M](implicit mbt: BaseMappableType[M]): ToMappable[HNil, M] = new ToMappable[HNil, M] { override def apply(l: HNil): M = mbt.base } }
Example 104
Source File: ComposeFreeMonads.scala From Freasy-Monad with MIT License | 5 votes |
package examples.scalaz import scalaz._ import scalaz.Id.Id import freasymonad.scalaz.free import scala.collection.mutable.ListBuffer import scala.io.StdIn import scala.language.{higherKinds, reflectiveCalls} // example based off https://github.com/typelevel/cats/blob/master/docs/src/main/tut/datatypes/freemonad.md#composing-free-monads-adts object ComposeFreeMonads extends App { @free trait Interact { type InteractF[A] = Free[Adt, A] sealed trait Adt[A] def ask(prompt: String): InteractF[String] def tell(msg: String): InteractF[Unit] } @free trait DataSource { type DataSourceF[A] = Free[Adt, A] sealed trait Adt[A] def addCat(a: String): DataSourceF[Unit] def getAllCats: DataSourceF[List[String]] def addAndGetAllCats(a: String): DataSourceF[List[String]] = for { _ <- addCat(a) c <- getAllCats } yield c } type ScalazApp[A] = Coproduct[DataSource.Adt, Interact.Adt, A] // program1 and program2 are the same. // This library lets you choose which style you like. def program1(implicit I: Interact.Injects[ScalazApp], D : DataSource.Injects[ScalazApp]): Free[ScalazApp, Unit] = { import I._, D._ for { cat <- ask("What's the kitty's name?") cats <- addAndGetAllCats(cat) _ <- tell(cats.toString) } yield () } val program2: Free[ScalazApp, Unit] = { import Interact.injectOps._, DataSource.injectOps._ for { cat <- ask[ScalazApp]("What's the kitty's name?") cats <- addAndGetAllCats[ScalazApp](cat) _ <- tell[ScalazApp](cats.toString) } yield () } val consoleCats = new Interact.Interp[Id] { def ask(prompt: String): Id[String] = { println(prompt) StdIn.readLine() } def tell(msg: String): Id[Unit] = println(msg) } val inMemoryDatasource = new DataSource.Interp[Id] { private[this] val memDataSet = new ListBuffer[String] def addCat(a: String): Id[Unit] = memDataSet.append(a) def getAllCats: Id[List[String]] = memDataSet.toList } // scalaz lacks a convenient `or` atm // https://github.com/scalaz/scalaz/issues/1222 implicit class NaturalTransformationOps[F[_], G[_]](val self: F ~> G) extends AnyVal { def or[H[_]](g: H ~> G): ({type λ[α] = Coproduct[F, H, α]})#λ ~> G = new (({type λ[α] = Coproduct[F, H, α]})#λ ~> G) { def apply[A](fa: Coproduct[F, H, A]): G[A] = fa.run.fold(self.apply, g.apply) } } val interpreter = inMemoryDatasource or consoleCats program1.foldMap(interpreter) program2.foldMap(interpreter) }
Example 105
Source File: MyPostgresProfile.scala From silhouette-vuejs-app with Apache License 2.0 | 5 votes |
package models.daos import com.github.tminglei.slickpg._ import play.api.libs.json.{JsValue, Json} import slick.basic.Capability import slick.jdbc.JdbcCapabilities import scala.language.higherKinds trait MyPostgresProfile extends ExPostgresProfile with PgArraySupport with PgDate2Support with PgRangeSupport with PgHStoreSupport with PgPlayJsonSupport with PgSearchSupport with PgNetSupport with PgLTreeSupport { def pgjson = "jsonb" // jsonb support is in postgres 9.4.0 onward; for 9.3.x use "json" import slick.ast._ import slick.ast.Library._ import slick.lifted.FunctionSymbolExtensionMethods._ // Add back `capabilities.insertOrUpdate` to enable native `upsert` support; for postgres 9.5+ override protected def computeCapabilities: Set[Capability] = super.computeCapabilities + JdbcCapabilities.insertOrUpdate override val api = MyAPI object MyAPI extends API with ArrayImplicits with DateTimeImplicits with JsonImplicits with NetImplicits with LTreeImplicits with RangeImplicits with HStoreImplicits with SearchImplicits with SearchAssistants { implicit val strListTypeMapper = new SimpleArrayJdbcType[String]("text").to(_.toList) implicit val playJsonArrayTypeMapper = new AdvancedArrayJdbcType[JsValue](pgjson, s => utils.SimpleArrayUtils.fromString[JsValue](Json.parse(_))(s).orNull, v => utils.SimpleArrayUtils.mkString[JsValue](_.toString())(v) ).to(_.toList) // Declare the name of an aggregate function: val ArrayAgg = new SqlAggregateFunction("array_agg") // Implement the aggregate function as an extension method: implicit class ArrayAggColumnQueryExtensionMethods[P, C[_]](val q: Query[Rep[P], _, C]) { def arrayAgg[B](implicit tm: TypedType[List[B]]) = ArrayAgg.column[List[B]](q.toNode) } } } object MyPostgresProfile extends MyPostgresProfile
Example 106
Source File: CollectionBuilder.scala From tethys with Apache License 2.0 | 5 votes |
package tethys.compat import scala.collection.generic.CanBuildFrom import scala.collection.mutable import scala.language.higherKinds trait CollectionBuilder[A, C] { def newBuilder: mutable.Builder[A, C] } object CollectionBuilder { implicit def seqCBFBuilder[A, C[_]](implicit cbf: CanBuildFrom[Nothing, A, C[A]]): CollectionBuilder[A, C[A]] = new CollectionBuilder[A, C[A]] { override def newBuilder: mutable.Builder[A, C[A]] = cbf() } implicit def mapCBFBuilder[K, V, M[_, _]](implicit cbf: CanBuildFrom[Nothing, (K, V), M[K, V]]): CollectionBuilder[(K, V), M[K, V]] = new CollectionBuilder[(K, V), M[K, V]] { override def newBuilder: mutable.Builder[(K, V), M[K, V]] = cbf() } }
Example 107
Source File: IterableReaders.scala From tethys with Apache License 2.0 | 5 votes |
package tethys.readers.instances import tethys.JsonReader import tethys.compat.CollectionBuilder import tethys.readers.tokens.TokenIterator import tethys.readers.{FieldName, ReaderError} import scala.annotation.tailrec import scala.collection.mutable import scala.language.higherKinds private[tethys] trait IterableReaders extends LowPriorityIterableReaders { implicit def shortIterableReader[C[X] <: Iterable[X]](implicit cb: CollectionBuilder[Short, C[Short]]): JsonReader[C[Short]] = new TraversableReader[Short, C] { override protected def appendBuilder(it: TokenIterator, builder: mutable.Builder[Short, C[Short]])(implicit fieldName: FieldName): Unit = { builder += PrimitiveReaders.ShortJsonReader.read(it) } } implicit def intIterableReader[C[X] <: Iterable[X]](implicit cb: CollectionBuilder[Int, C[Int]]): JsonReader[C[Int]] = new TraversableReader[Int, C] { override protected def appendBuilder(it: TokenIterator, builder: mutable.Builder[Int, C[Int]])(implicit fieldName: FieldName): Unit = { builder += PrimitiveReaders.IntJsonReader.read(it) } } implicit def longIterableReader[C[X] <: Iterable[X]](implicit cb: CollectionBuilder[Long, C[Long]]): JsonReader[C[Long]] = new TraversableReader[Long, C] { override protected def appendBuilder(it: TokenIterator, builder: mutable.Builder[Long, C[Long]])(implicit fieldName: FieldName): Unit = { builder += PrimitiveReaders.LongJsonReader.read(it) } } implicit def floatIterableReader[C[X] <: Iterable[X]](implicit cb: CollectionBuilder[Float, C[Float]]): JsonReader[C[Float]] = new TraversableReader[Float, C] { override protected def appendBuilder(it: TokenIterator, builder: mutable.Builder[Float, C[Float]])(implicit fieldName: FieldName): Unit = { builder += PrimitiveReaders.FloatJsonReader.read(it) } } implicit def doubleIterableReader[C[X] <: Iterable[X]](implicit cb: CollectionBuilder[Double, C[Double]]): JsonReader[C[Double]] = new TraversableReader[Double, C] { override protected def appendBuilder(it: TokenIterator, builder: mutable.Builder[Double, C[Double]])(implicit fieldName: FieldName): Unit = { builder += PrimitiveReaders.DoubleJsonReader.read(it) } } implicit def booleanIterableReader[C[X] <: Iterable[X]](implicit cb: CollectionBuilder[Boolean, C[Boolean]]): JsonReader[C[Boolean]] = new TraversableReader[Boolean, C] { override protected def appendBuilder(it: TokenIterator, builder: mutable.Builder[Boolean, C[Boolean]])(implicit fieldName: FieldName): Unit = { builder += PrimitiveReaders.BooleanJsonReader.read(it) } } } private[tethys] trait LowPriorityIterableReaders extends LowPriorityJsonReaders { implicit def iterableReader[A, C[X] <: Iterable[X]](implicit jsonReader: JsonReader[A], collectionBuilder: CollectionBuilder[A, C[A]]): JsonReader[C[A]] = new TraversableReader[A, C] { override protected def appendBuilder(it: TokenIterator, builder: mutable.Builder[A, C[A]])(implicit fieldName: FieldName): Unit = { builder += jsonReader.read(it) } } protected abstract class TraversableReader[A, C[X] <: Iterable[X]](implicit cb: CollectionBuilder[A, C[A]]) extends JsonReader[C[A]] { protected def appendBuilder(it: TokenIterator, builder: mutable.Builder[A, C[A]])(implicit fieldName: FieldName): Unit override def read(it: TokenIterator)(implicit fieldName: FieldName): C[A] = { if (it.currentToken().isArrayStart) recRead(0, it.next(), cb.newBuilder) else ReaderError.wrongJson(s"Expected array start but found: ${it.currentToken()}") } @tailrec private def recRead(i: Int, it: TokenIterator, builder: mutable.Builder[A, C[A]]) (implicit fieldName: FieldName): C[A] = { it.currentToken() match { case token if token.isEmpty => ReaderError.wrongJson("Unexpected end of input") case token if token.isArrayEnd => it.nextToken() builder.result() case _ => appendBuilder(it, builder)(fieldName.appendArrayIndex(i)) recRead(i + 1, it, builder) } } } }
Example 108
Source File: JsonWriter.scala From tethys with Apache License 2.0 | 5 votes |
package tethys import tethys.writers.instances.{AllJsonWriters, SimpleJsonObjectWriter} import tethys.writers.tokens.TokenWriter import scala.language.higherKinds trait JsonWriter[@specialized(specializations) A] { self => def write(name: String, value: A, tokenWriter: TokenWriter): Unit = { tokenWriter.writeFieldName(name) write(value, tokenWriter) } def write(value: A, tokenWriter: TokenWriter): Unit def contramap[B](fun: B => A): JsonWriter[B] = new JsonWriter[B] { override def write(name: String, value: B, tokenWriter: TokenWriter): Unit = { self.write(name, fun(value), tokenWriter) } override def write(value: B, tokenWriter: TokenWriter): Unit = { self.write(fun(value), tokenWriter) } } } object JsonWriter extends AllJsonWriters { def apply[A](implicit jsonWriter: JsonWriter[A]): JsonWriter[A] = jsonWriter def obj[A]: SimpleJsonObjectWriter[A] = SimpleJsonObjectWriter[A] }
Example 109
Source File: IterableWriters.scala From tethys with Apache License 2.0 | 5 votes |
package tethys.writers.instances import tethys._ import tethys.writers.tokens.TokenWriter import scala.language.higherKinds private[tethys] trait IterableWriters extends LowPriorityJsonWriters { final implicit def iterableWriter[A, C[X] <: Iterable[X]](implicit valueWriter: JsonWriter[A]): JsonWriter[C[A]] = new IterableWriter[A, C](valueWriter) { override def iterator(c: C[A]): Iterator[A] = c.iterator } abstract class IterableWriter[A, C[_]](valueWriter: JsonWriter[A]) extends JsonWriter[C[A]] { def iterator(c: C[A]): Iterator[A] override def write(value: C[A], tokenWriter: TokenWriter): Unit = { tokenWriter.writeArrayStart() val valueIterator = iterator(value) while(valueIterator.hasNext) { val v = valueIterator.next() valueWriter.write(v, tokenWriter) } tokenWriter.writeArrayEnd() } } }
Example 110
Source File: CollectionBuilder.scala From tethys with Apache License 2.0 | 5 votes |
package tethys.compat import scala.collection.{IterableFactory, IterableFactoryDefaults, MapFactory, mutable} import scala.language.experimental.macros import scala.language.higherKinds import scala.reflect.macros.blackbox trait CollectionBuilder[A, C] { def newBuilder: mutable.Builder[A, C] } object CollectionBuilder { final class IterableFactoryCollectionBuilder[A, C[_]](factory: IterableFactory[C]) extends CollectionBuilder[A, C[A]] { override def newBuilder: mutable.Builder[A, C[A]] = factory.newBuilder[A] } final class MapFactoryCollectionBuilder[K, V, M[_, _]](factory: MapFactory[M]) extends CollectionBuilder[(K, V), M[K, V]] { override def newBuilder: mutable.Builder[(K, V), M[K, V]] = factory.newBuilder[K, V] } implicit def iterableFactoryCollectionBuilder[A, C[X] <: IterableFactoryDefaults[X, C]]: IterableFactoryCollectionBuilder[A, C] = macro CollectionBuilderMacroImpl.fromIterableFactory[A, C] implicit def mapFactoryCollectionBuilder[K, V, M[X, Y] <: Map[X, Y]]: MapFactoryCollectionBuilder[K, V, M] = macro CollectionBuilderMacroImpl.fromMapFactory[K, V, M] private class CollectionBuilderMacroImpl(val c: blackbox.Context) { import c.universe._ def fromIterableFactory[A, C[X] <: IterableFactoryDefaults[X, C]](implicit A: WeakTypeTag[A], C: WeakTypeTag[C[A]]): Tree = { val ref = C.tpe.typeSymbol.companion q"new tethys.compat.CollectionBuilder.IterableFactoryCollectionBuilder[${A.tpe}, ${C.tpe}]($ref)" } def fromMapFactory[K, V, M[X, Y] <: Map[X, Y]](implicit K: WeakTypeTag[K], V: WeakTypeTag[V], M: WeakTypeTag[M[K, V]]): Tree = { val ref = M.tpe.typeSymbol.companion q"new tethys.compat.CollectionBuilder.MapFactoryCollectionBuilder[${K.tpe}, ${V.tpe}, ${M.tpe}]($ref)" } } }
Example 111
Source File: field.scala From cron4s with Apache License 2.0 | 5 votes |
package cron4s.syntax import cron4s.{CronField, CronUnit} import cron4s.expr.FieldExpr import cron4s.base.Predicate import scala.language.higherKinds private[syntax] class FieldExprOps[E[_ <: CronField], F <: CronField]( self: E[F], tc: FieldExpr[E, F] ) extends EnumeratedOps[E[F]](self, tc) { def matches: Predicate[Int] = tc.matches(self) def implies[EE[_ <: CronField]](ee: EE[F])(implicit EE: FieldExpr[EE, F]): Boolean = tc.implies(self)(ee) def impliedBy[EE[_ <: CronField]](ee: EE[F])(implicit EE: FieldExpr[EE, F]): Boolean = tc.impliedBy(self)(ee) def unit: CronUnit[F] = tc.unit(self) } private[syntax] trait FieldExprSyntax extends EnumeratedSyntax { implicit def toExprOps[E[_ <: CronField], F <: CronField]( target: E[F] )(implicit tc: FieldExpr[E, F]): FieldExprOps[E, F] = new FieldExprOps[E, F](target, tc) } object field extends FieldExprSyntax
Example 112
Source File: package.scala From typedapi with MIT License | 5 votes |
package typedapi.client import scala.language.higherKinds package object test { type TestClientM = ClientManager[Unit] val clientManager: TestClientM = ClientManager((), "", 0) def testRawGet[F[_]](pure: ReqInput => F[ReqInput]) = new RawGetRequest[Unit, F] { type Resp = ReqInput def apply(uri: List[String], queries: Map[String, List[String]], headers: Map[String, String], cm: TestClientM): F[Resp] = pure(ReqInput("GET", uri, queries, headers)) } def testGet[F[_], A](f: ReqInput => F[A]) = new GetRequest[Unit, F, A] { def apply(uri: List[String], queries: Map[String, List[String]], headers: Map[String, String], cm: TestClientM): F[A] = f(ReqInput("GET", uri, queries, headers)) } def testRawPut[F[_]](pure: ReqInput => F[ReqInput]) = new RawPutRequest[Unit, F] { type Resp = ReqInput def apply(uri: List[String], queries: Map[String, List[String]], headers: Map[String, String], cm: TestClientM): F[Resp] = pure(ReqInput("PUT", uri, queries, headers)) } def testPut[F[_], A](f: ReqInput => F[A]) = new PutRequest[Unit, F, A] { def apply(uri: List[String], queries: Map[String, List[String]], headers: Map[String, String], cm: TestClientM): F[A] = f(ReqInput("PUT", uri, queries, headers)) } def testRawPutWithBody[F[_], Bd](pure: ReqInputWithBody[Bd] => F[ReqInputWithBody[Bd]]) = new RawPutWithBodyRequest[Unit, F, Bd] { type Resp = ReqInputWithBody[Bd] def apply(uri: List[String], queries: Map[String, List[String]], headers: Map[String, String], body: Bd, cm: TestClientM): F[Resp] = pure(ReqInputWithBody("PUT", uri, queries, headers, body)) } def testPutWithBody[F[_], Bd, A](f: ReqInputWithBody[Bd] => F[A]) = new PutWithBodyRequest[Unit, F, Bd, A] { def apply(uri: List[String], queries: Map[String, List[String]], headers: Map[String, String], body: Bd, cm: TestClientM): F[A] = f(ReqInputWithBody("PUT", uri, queries, headers, body)) } def testRawPost[F[_]](pure: ReqInput => F[ReqInput]) = new RawPostRequest[Unit, F] { type Resp = ReqInput def apply(uri: List[String], queries: Map[String, List[String]], headers: Map[String, String], cm: TestClientM): F[Resp] = pure(ReqInput("POST", uri, queries, headers)) } def testPost[F[_], A](f: ReqInput => F[A]) = new PostRequest[Unit, F, A] { def apply(uri: List[String], queries: Map[String, List[String]], headers: Map[String, String], cm: TestClientM): F[A] = f(ReqInput("POST", uri, queries, headers)) } def testRawPostWithBody[F[_], Bd](pure: ReqInputWithBody[Bd] => F[ReqInputWithBody[Bd]]) = new RawPostWithBodyRequest[Unit, F, Bd] { type Resp = ReqInputWithBody[Bd] def apply(uri: List[String], queries: Map[String, List[String]], headers: Map[String, String], body: Bd, cm: TestClientM): F[Resp] = pure(ReqInputWithBody("POST", uri, queries, headers, body)) } def testPostWithBody[F[_], Bd, A](f: ReqInputWithBody[Bd] => F[A]) = new PostWithBodyRequest[Unit, F, Bd, A] { def apply(uri: List[String], queries: Map[String, List[String]], headers: Map[String, String], body: Bd, cm: TestClientM): F[A] = f(ReqInputWithBody("POST", uri, queries, headers, body)) } def testRawDelete[F[_]](pure: ReqInput => F[ReqInput]) = new RawDeleteRequest[Unit, F] { type Resp = ReqInput def apply(uri: List[String], queries: Map[String, List[String]], headers: Map[String, String], cm: TestClientM): F[Resp] = pure(ReqInput("DELETE", uri, queries, headers)) } def testDelete[F[_], A](f: ReqInput => F[A]) = new DeleteRequest[Unit, F, A] { def apply(uri: List[String], queries: Map[String, List[String]], headers: Map[String, String], cm: TestClientM): F[A] = f(ReqInput("DELETE", uri, queries, headers)) } }
Example 113
Source File: Endpoint.scala From typedapi with MIT License | 5 votes |
package typedapi.server import typedapi.shared._ import shapeless._ import shapeless.labelled.FieldType import shapeless.ops.function._ import scala.language.higherKinds def from(fn: Fn): Endpoint[El, KIn, VIn, M, ROut, F, Out] = new Endpoint[El, KIn, VIn, M, ROut, F, Out](method, extractor, headers) { private val fin = fnToVIn(fn) def apply(in: VIn): F[Result[Out]] = fin(in) } } def apply[H <: HList, FH <: HList, El <: HList, KIn <: HList, VIn <: HList, ROut, Fn, M <: MethodType, MT <: MediaType, Out] (apiList: ApiTypeCarrier[H]) (implicit filter: FilterClientElements.Aux[H, FH], folder: Lazy[TypeLevelFoldLeft.Aux[FH, Unit, (El, KIn, VIn, M, FieldType[MT, Out])]], extractor: RouteExtractor.Aux[El, KIn, VIn, M, HNil, ROut], methodShow: MethodToString[M], serverHeaders: ServerHeaderExtractor[El], inToFn: Lazy[FnFromProduct.Aux[VIn => F[Result[Out]], Fn]], fnToVIn: Lazy[FnToProduct.Aux[Fn, VIn => F[Result[Out]]]]): Derivation[El, KIn, VIn, M, ROut, Fn, Out] = new Derivation[El, KIn, VIn, M, ROut, Fn, Out](extractor, methodShow.show, serverHeaders(Map.empty), fnToVIn.value) }
Example 114
Source File: package.scala From typedapi with MIT License | 5 votes |
package typedapi import typedapi.shared._ import shapeless._ import shapeless.ops.hlist.Mapper import scala.language.higherKinds package object server extends TypeLevelFoldLeftLowPrio with TypeLevelFoldLeftListLowPrio with WitnessToStringLowPrio with ApiTransformer { val SC = StatusCodes type Result[A] = Either[HttpError, (SuccessCode, A)] def successWith[A](code: SuccessCode)(a: A): Result[A] = Right(code -> a) def success[A](a: A): Result[A] = successWith(StatusCodes.Ok)(a) def errorWith[A](code: ErrorCode, message: String): Result[A] = Left(HttpError(code, message)) def derive[F[_]]: ExecutableDerivation[F] = new ExecutableDerivation[F] def mount[S, El <: HList, KIn <: HList, VIn <: HList, M <: MethodType, ROut, F[_], FOut, Req, Resp, Out] (server: ServerManager[S], endpoint: Endpoint[El, KIn, VIn, M, ROut, F, FOut]) (implicit executor: EndpointExecutor.Aux[Req, El, KIn, VIn, M, ROut, F, FOut, Resp], mounting: MountEndpoints.Aux[S, Req, Resp, Out]): Out = mounting(server, List(new Serve[executor.R, executor.Out] { def options(eReq: EndpointRequest): Option[(String, Map[String, String])] = { endpoint.extractor(eReq, HNil) match { case Right(_) => Some((endpoint.method, endpoint.headers)) case _ => None } } def apply(req: executor.R, eReq: EndpointRequest): Either[ExtractionError, executor.Out] = executor(req, eReq, endpoint) })) def deriveAll[F[_]]: ExecutableCompositionDerivation[F] = new ExecutableCompositionDerivation[F] object endpointToServe extends Poly1 { implicit def default[El <: HList, KIn <: HList, VIn <: HList, M <: MethodType, ROut, F[_], FOut](implicit executor: EndpointExecutor[El, KIn, VIn, M, ROut, F, FOut]) = at[Endpoint[El, KIn, VIn, M, ROut, F, FOut]] { endpoint => new Serve[executor.R, executor.Out] { def options(eReq: EndpointRequest): Option[(String, Map[String, String])] = { endpoint.extractor(eReq, HNil) match { case Right(_) => Some((endpoint.method, endpoint.headers)) case _ => None } } def apply(req: executor.R, eReq: EndpointRequest): Either[ExtractionError, executor.Out] = executor(req, eReq, endpoint) } } } def mount[S, End <: HList, Serv <: HList, Req, Resp, Out](server: ServerManager[S], end: End)(implicit mapper: Mapper.Aux[endpointToServe.type, End, Serv], toList: ServeToList[Serv, Req, Resp], mounting: MountEndpoints.Aux[S, Req, Resp, Out]): Out = mounting(server, toList(end.map(endpointToServe))) }
Example 115
Source File: ExportedMagnolia.scala From pureconfig with Mozilla Public License 2.0 | 5 votes |
package pureconfig.module.magnolia import magnolia.Magnolia import pureconfig.Exported import scala.language.higherKinds import scala.reflect.macros.whitebox // Wrap the output of Magnolia in an Exported to force it to a lower priority. // This seems to work, despite magnolia hardcode checks for `macroApplication` symbol // and relying on getting an diverging implicit expansion error for auto-mode. // Thankfully at least it doesn't check the output type of its `macroApplication` object ExportedMagnolia { def exportedMagnolia[TC[_], A: c.WeakTypeTag](c: whitebox.Context): c.Expr[Exported[TC[A]]] = { val magnoliaTree = c.Expr[TC[A]](Magnolia.gen[A](c)) c.universe.reify(Exported(magnoliaTree.splice)) } }
Example 116
Source File: ValueClassSuite.scala From pureconfig with Mozilla Public License 2.0 | 5 votes |
package pureconfig.module.magnolia import scala.language.higherKinds import pureconfig._ import pureconfig.module.magnolia.auto.reader._ import pureconfig.module.magnolia.auto.writer._ import shapeless.test.illTyped // NOTE: behavior differs from pureconfig.generic (value classes also need to be case classes) final case class IntWrapper(inner: Int) extends AnyVal { override def toString: String = s"IntWrapper($inner)" } final case class PrivateFloatValue private (value: Float) extends AnyVal final case class GenericValue[A] private (t: A) extends AnyVal { override def toString: String = "GenericValue(" + t.toString + ")" } object GenericValue { def from[A](t: A): GenericValue[A] = new GenericValue[A](t) } trait Read[A] { def read(str: String): A } object Read { def apply[A](implicit readT: Read[A]): Read[A] = readT implicit val badReadString = new Read[String] { override def read(str: String): String = "" } } class ValueClassSuite extends BaseSuite { behavior of "ConfigConvert for Value Classes" checkRead[IntWrapper](ConfigWriter.forPrimitive[Int].to(1) -> new IntWrapper(1)) checkWrite[IntWrapper](new IntWrapper(1) -> ConfigWriter.forPrimitive[Int].to(1)) "ConfigReader[PrivateFloatValue]" should "not be derivable because the constructor is private" in { illTyped("pureconfig.ConfigReader[PrivateFloatValue]") } { implicit def genericValueReader[A](implicit readT: Read[A]): ConfigReader[GenericValue[A]] = ConfigReader.fromString(s => Right(GenericValue.from(readT.read(s)))) "ConfigReader" should " should be able to override value classes ConfigReader" in { val reader = ConfigReader[GenericValue[String]] val expected = Right(GenericValue.from("")) val configValue = ConfigWriter.forPrimitive[String].to("foobar") reader.from(configValue) shouldEqual expected } } }
Example 117
Source File: TupleConvertersSuite.scala From pureconfig with Mozilla Public License 2.0 | 5 votes |
package pureconfig.module.magnolia import scala.collection.JavaConverters._ import scala.language.higherKinds import com.typesafe.config.{ ConfigValueFactory, ConfigValueType } import org.scalacheck.ScalacheckShapeless._ import pureconfig._ import pureconfig.error._ import pureconfig.module.magnolia.auto.reader._ import pureconfig.module.magnolia.auto.writer._ class TupleConvertersSuite extends BaseSuite { behavior of "ConfigConvert" // Check arbitrary Tuples checkArbitrary[Tuple1[Int]] checkArbitrary[(String, Int)] checkArbitrary[(Int, (Long, String), Boolean)] // Check arbitrary Tuples with custom types case class Foo(a: Int, b: String) checkArbitrary[(Long, Foo, Boolean, Foo)] // Check readers from objects and lists checkRead[(String, Int)](ConfigValueFactory.fromMap(Map("_1" -> "one", "_2" -> 2).asJava) -> (("one", 2))) checkRead[(String, Int)](ConfigValueFactory.fromMap(Map("0" -> "one", "1" -> 2).asJava) -> (("one", 2))) checkRead[(String, Int)](ConfigValueFactory.fromIterable(List("one", 2).asJava) -> (("one", 2))) // Check writers checkWrite[Tuple1[Int]](Tuple1(1) -> ConfigValueFactory.fromIterable(List(1).asJava)) checkWrite[(String, Int)](("one", 2) -> ConfigValueFactory.fromIterable(List("one", 2).asJava)) checkWrite[(Int, (Long, String), Boolean)]((1, (2l, "three"), false) -> ConfigValueFactory.fromIterable(List(1, List(2l, "three").asJava, false).asJava)) // Check errors checkFailures[(String, Int)]( ConfigValueFactory.fromAnyRef(Map("_1" -> "one", "_2" -> "two").asJava) -> ConfigReaderFailures( ConvertFailure(WrongType(ConfigValueType.STRING, Set(ConfigValueType.NUMBER)), emptyConfigOrigin, "_2"))) checkFailures[(String, Int)]( ConfigValueFactory.fromIterable(List("one", "two").asJava) -> ConfigReaderFailures( ConvertFailure(WrongType(ConfigValueType.STRING, Set(ConfigValueType.NUMBER)), emptyConfigOrigin, "1"))) checkFailures[(Int, Int, Int)]( ConfigValueFactory.fromIterable(List(1, "one").asJava) -> ConfigReaderFailures( ConvertFailure(WrongSizeList(3, 2), emptyConfigOrigin, ""))) checkFailures[(Int, Int, Int)]( ConfigValueFactory.fromAnyRef(Map("_1" -> "one", "_2" -> 2).asJava) -> ConfigReaderFailures( ConvertFailure(WrongType(ConfigValueType.STRING, Set(ConfigValueType.NUMBER)), emptyConfigOrigin, "_1"), ConvertFailure(KeyNotFound("_3", Set()), emptyConfigOrigin, ""))) checkFailures[(String, Int)]( ConfigValueFactory.fromAnyRef("str") -> ConfigReaderFailures( ConvertFailure(WrongType(ConfigValueType.STRING, Set(ConfigValueType.LIST)), emptyConfigOrigin, ""))) }
Example 118
Source File: DerivationModesSuite.scala From pureconfig with Mozilla Public License 2.0 | 5 votes |
package pureconfig.module.magnolia import scala.language.higherKinds import com.typesafe.config.ConfigFactory import pureconfig._ import shapeless.test.illTyped class DerivationModesSuite extends BaseSuite { sealed trait Entity case class Person(name: String, surname: String) extends Entity case class Place(name: String, lat: Double, lon: Double) extends Entity val person = Person("John", "Doe") val conf = ConfigFactory.parseString("{ type: person, name: John, surname: Doe }") case class CustomCaseClass(customObject: CustomObject, mapCustomObject: Map[String, CustomObject], mapListCustomObject: Map[String, List[CustomObject]]) case class CustomObject(value: Int) object CustomObject { implicit val pureconfigReader: ConfigReader[CustomObject] = ConfigReader.fromStringOpt { case "eaaxacaca" => Some(CustomObject(453)) case "a" => Some(CustomObject(45)) case _ => Some(CustomObject(1)) } implicit val pureconfigWriter: ConfigWriter[CustomObject] = ConfigWriter.toString { case CustomObject(453) => "eaaxacaca" case CustomObject(45) => "a" case _ => "cvbc" } } val customCaseClass = CustomCaseClass( CustomObject(453), Map("a" -> CustomObject(453), "b" -> CustomObject(45)), Map("x" -> List(CustomObject(45), CustomObject(453), CustomObject(1)))) val customConf = ConfigFactory.parseString( """{ | custom-object = "eaaxacaca" | map-custom-object { a = "eaaxacaca", b = "a" } | map-list-custom-object { x = ["a", "eaaxacaca", "cvbc"]} |}""".stripMargin) behavior of "default" it should "not provide instance derivation for products and coproducts out-of-the-box" in { illTyped("loadConfig[Entity](conf)") illTyped("ConfigWriter[Entity]") } behavior of "semiauto" it should "not provide instance derivation for products and coproducts out-of-the-box" in { illTyped("{ import pureconfig.module.magnolia.reader.semiauto._; loadConfig[Entity](conf) }") illTyped("{ import pureconfig.module.magnolia.reader.semiauto._; ConfigWriter[Entity] }") } it should "provide methods to derive readers on demand" in { import pureconfig.module.magnolia.semiauto.reader._ implicit val personReader = deriveReader[Person] implicit val placeReader = deriveReader[Place] implicit val entityReader = deriveReader[Entity] ConfigReader[Entity].from(conf.root) shouldBe Right(person) } it should "provide methods to derive writers on demand" in { import pureconfig.module.magnolia.semiauto.writer._ implicit val personWriter = deriveWriter[Person] implicit val placeWriter = deriveWriter[Place] implicit val entityWriter = deriveWriter[Entity] ConfigWriter[Entity].to(person) shouldBe conf.root() } behavior of "auto" it should "provide instance derivation for products and coproducts out-of-the-box" in { import pureconfig.module.magnolia.auto.reader._ import pureconfig.module.magnolia.auto.writer._ ConfigReader[Entity].from(conf.root) shouldBe Right(person) ConfigWriter[Entity].to(person) shouldBe conf.root() } it should "use existing reader and writer instances when they exist" in { import pureconfig.module.magnolia.auto.reader._ import pureconfig.module.magnolia.auto.writer._ ConfigReader[CustomCaseClass].from(customConf.root) shouldBe Right(customCaseClass) ConfigWriter[CustomCaseClass].to(customCaseClass) shouldBe customConf.root() } }
Example 119
Source File: CoproductConvertersSuite.scala From pureconfig with Mozilla Public License 2.0 | 5 votes |
package pureconfig.module.magnolia import scala.language.higherKinds import com.typesafe.config.{ ConfigFactory, ConfigObject, ConfigValueFactory } import org.scalacheck.{ Arbitrary, Gen } import pureconfig._ import pureconfig.error._ import pureconfig.module.magnolia.auto.reader._ import pureconfig.module.magnolia.auto.writer._ class CoproductConvertersSuite extends BaseSuite { behavior of "ConfigConvert" val genBirdConfig: Gen[BirdConfig] = Arbitrary.arbBool.arbitrary.map(BirdConfig.apply) val genCatConfig: Gen[CatConfig] = Arbitrary.arbInt.arbitrary.map(CatConfig.apply) val genDogConfig: Gen[DogConfig] = Arbitrary.arbInt.arbitrary.map(DogConfig.apply) val genAnimalConfig: Gen[AnimalConfig] = Gen.oneOf(genBirdConfig, genCatConfig, genDogConfig) implicit val arbAnimalConfig = Arbitrary(genAnimalConfig) checkArbitrary[AnimalConfig] it should "read disambiguation information on sealed families by default" in { val conf = ConfigFactory.parseString("{ type = dog-config, age = 2 }") ConfigConvert[AnimalConfig].from(conf.root()) shouldEqual Right(DogConfig(2)) } it should "write disambiguation information on sealed families by default" in { val conf = ConfigConvert[AnimalConfig].to(DogConfig(2)) conf shouldBe a[ConfigObject] conf.asInstanceOf[ConfigObject].get("type") shouldEqual ConfigValueFactory.fromAnyRef("dog-config") } it should "return a proper ConfigReaderFailure if the hint field in a coproduct is missing" in { val conf = ConfigFactory.parseString("{ can-fly = true }") ConfigConvert[AnimalConfig].from(conf.root()) should failWithType[KeyNotFound] } it should "return a proper ConfigReaderFailure when a coproduct config is missing" in { case class AnimalCage(animal: AnimalConfig) ConfigConvert[AnimalCage].from(ConfigFactory.empty().root()) should failWithType[KeyNotFound] } }
Example 120
Source File: CoproductHintSuite.scala From pureconfig with Mozilla Public License 2.0 | 5 votes |
package pureconfig.module.magnolia import scala.language.higherKinds import com.typesafe.config._ import pureconfig._ import pureconfig.error._ import pureconfig.generic._ import pureconfig.generic.error.{ CoproductHintException, UnexpectedValueForFieldCoproductHint } import pureconfig.module.magnolia.auto.reader._ import pureconfig.module.magnolia.auto.writer._ class CoproductHintSuite extends BaseSuite { behavior of "CoproductHint" { implicit val hint = new FieldCoproductHint[AnimalConfig]("which-animal") { override def fieldValue(name: String) = name.dropRight("Config".length) } it should "read values as expected when using a FieldCoproductHint" in { val conf = ConfigFactory.parseString("{ which-animal = Dog, age = 2 }") ConfigConvert[AnimalConfig].from(conf.root()) shouldEqual Right(DogConfig(2)) } it should "write values as expected when using a FieldCoproductHint" in { val conf = ConfigConvert[AnimalConfig].to(DogConfig(2)) conf shouldBe a[ConfigObject] conf.asInstanceOf[ConfigObject].get("which-animal") shouldEqual ConfigValueFactory.fromAnyRef("Dog") } it should "fail to read values that are not objects when using a FieldCoproductHint" in { val conf = ConfigValueFactory.fromAnyRef("Dog") ConfigConvert[AnimalConfig].from(conf) should failWith( WrongType(ConfigValueType.STRING, Set(ConfigValueType.OBJECT))) } it should "fail to read values in the discriminating field that are not strings when using a FieldCoproductHint" in { val conf = ConfigFactory.parseString("{ which-animal { type = Dog }, age = 2 }") ConfigConvert[AnimalConfig].from(conf.root()) should be(Left( ConfigReaderFailures( ConvertFailure(WrongType(ConfigValueType.OBJECT, Set(ConfigValueType.STRING)), stringConfigOrigin(1), "which-animal")))) } it should "fail with an appropriate reason if an unexpected value is found at the discriminating field when using a FieldCoproductHint" in { val conf = ConfigFactory.parseString("{ which-animal = unexpected, age = 2 }") ConfigConvert[AnimalConfig].from(conf.root()) should be(Left( ConfigReaderFailures( ConvertFailure(UnexpectedValueForFieldCoproductHint(ConfigValueFactory.fromAnyRef("unexpected")), stringConfigOrigin(1), "which-animal")))) } it should "fail to read when the hint field conflicts with a field of an option when using a FieldCoproductHint" in { sealed trait Conf case class AmbiguousConf(typ: String) extends Conf implicit val hint = new FieldCoproductHint[Conf]("typ") val cc = implicitly[ConfigConvert[Conf]] val conf = ConfigFactory.parseString("{ typ = ambiguous-conf }") cc.from(conf.root()) should failWithType[KeyNotFound] // "typ" should not be passed to the coproduct option val ex = the[CoproductHintException] thrownBy cc.to(AmbiguousConf("ambiguous-conf")) ex.failure shouldEqual CollidingKeys("typ", ConfigValueFactory.fromAnyRef("ambiguous-conf")) } } { implicit val hint = new FirstSuccessCoproductHint[AnimalConfig] it should "read values as expected when using a FirstSuccessCoproductHint" in { val conf = ConfigFactory.parseString("{ can-fly = true }") ConfigConvert[AnimalConfig].from(conf.root()) shouldBe Right(BirdConfig(true)) } it should "write values as expected when using a FirstSuccessCoproductHint" in { val conf = ConfigConvert[AnimalConfig].to(DogConfig(2)) conf shouldBe a[ConfigObject] conf.asInstanceOf[ConfigObject].get("which-animal") shouldBe null } } }
Example 121
Source File: package.scala From pureconfig with Mozilla Public License 2.0 | 5 votes |
package pureconfig.module.catseffect import scala.language.higherKinds import scala.reflect.ClassTag import cats.effect.{ Blocker, ContextShift, Sync } import pureconfig.{ ConfigReader, ConfigSource, Derivation } import pureconfig.module.catseffect package object syntax { implicit class CatsEffectConfigSource(private val cs: ConfigSource) extends AnyVal { @inline final def loadF[F[_], A](blocker: Blocker)(implicit F: Sync[F], csf: ContextShift[F], reader: Derivation[ConfigReader[A]], ct: ClassTag[A]): F[A] = catseffect.loadF(cs, blocker) @deprecated("Use `cs.loadF[F, A](blocker)` instead", "0.12.3") def loadF[F[_], A](implicit F: Sync[F], reader: Derivation[ConfigReader[A]], ct: ClassTag[A]): F[A] = catseffect.loadF(cs) } }
Example 122
Source File: package.scala From pureconfig with Mozilla Public License 2.0 | 5 votes |
package pureconfig.module import _root_.cats.data._ import _root_.cats.kernel.Order import _root_.cats.{ Alternative, Foldable } import _root_.cats.implicits._ import pureconfig.{ ConfigReader, ConfigWriter, Exported } import scala.collection.immutable.{ SortedMap, SortedSet } import scala.language.higherKinds import scala.reflect.ClassTag package object cats { private[pureconfig] def fromNonEmpty[A, B](reader: ConfigReader[A])(fromX: A => Option[B])(implicit ct: ClassTag[A]): ConfigReader[B] = reader.emap(x => fromX(x).toRight(EmptyTraversableFound(ct.toString))) implicit def nonEmptyListReader[A](implicit reader: ConfigReader[List[A]]): ConfigReader[NonEmptyList[A]] = fromNonEmpty(reader)(NonEmptyList.fromList) implicit def nonEmptyListWriter[A](implicit writer: ConfigWriter[List[A]]): ConfigWriter[NonEmptyList[A]] = writer.contramap(_.toList) implicit def nonEmptyVectorReader[A](implicit reader: ConfigReader[Vector[A]]): ConfigReader[NonEmptyVector[A]] = fromNonEmpty(reader)(NonEmptyVector.fromVector) implicit def nonEmptyVectorWriter[A](implicit writer: ConfigWriter[Vector[A]]): ConfigWriter[NonEmptyVector[A]] = writer.contramap(_.toVector) implicit def nonEmptySetReader[A](implicit reader: ConfigReader[SortedSet[A]]): ConfigReader[NonEmptySet[A]] = fromNonEmpty(reader)(NonEmptySet.fromSet) implicit def nonEmptySetWriter[A](implicit writer: ConfigWriter[SortedSet[A]]): ConfigWriter[NonEmptySet[A]] = writer.contramap(_.toSortedSet) implicit def nonEmptyMapReader[A, B](implicit reader: ConfigReader[Map[A, B]], ord: Order[A]): ConfigReader[NonEmptyMap[A, B]] = fromNonEmpty(reader)(x => NonEmptyMap.fromMap(SortedMap(x.toSeq: _*)(ord.toOrdering))) implicit def nonEmptyMapWriter[A, B](implicit writer: ConfigWriter[Map[A, B]]): ConfigWriter[NonEmptyMap[A, B]] = writer.contramap(_.toSortedMap) // For emptiable foldables not covered by TraversableOnce reader/writer, e.g. Chain. implicit def lowPriorityNonReducibleReader[A, F[_]: Foldable: Alternative](implicit reader: ConfigReader[List[A]]): Exported[ConfigReader[F[A]]] = Exported(reader.map(to => (to foldRight Alternative[F].empty[A])(_.pure[F] <+> _))) implicit def lowPriorityNonReducibleWriter[A, F[_]: Foldable: Alternative](implicit writer: ConfigWriter[List[A]]): Exported[ConfigWriter[F[A]]] = Exported(writer.contramap(_.toList)) implicit def nonEmptyChainReader[A](implicit reader: ConfigReader[Chain[A]]): ConfigReader[NonEmptyChain[A]] = fromNonEmpty(reader)(NonEmptyChain.fromChain) implicit def nonEmptyChainWriter[A](implicit writer: ConfigWriter[Chain[A]]): ConfigWriter[NonEmptyChain[A]] = writer.contramap(_.toChain) }
Example 123
Source File: CollectionReaders.scala From pureconfig with Mozilla Public License 2.0 | 5 votes |
package pureconfig import scala.language.higherKinds import scala.reflect.ClassTag trait CollectionReaders { implicit def optionReader[A](implicit conv: Derivation[ConfigReader[A]]): ConfigReader[Option[A]] = new ConfigReader[Option[A]] with ReadsMissingKeys { override def from(cur: ConfigCursor): ConfigReader.Result[Option[A]] = { if (cur.isUndefined || cur.isNull) Right(None) else conv.value.from(cur).right.map(Some(_)) } } implicit def traversableReader[A, F[A] <: TraversableOnce[A]]( implicit configConvert: Derivation[ConfigReader[A]], cbf: FactoryCompat[A, F[A]]) = new ConfigReader[F[A]] { override def from(cur: ConfigCursor): ConfigReader.Result[F[A]] = { cur.fluent.mapList { valueCur => configConvert.value.from(valueCur) }.right.map { coll => val builder = cbf.newBuilder() (builder ++= coll).result() } } } implicit def mapReader[A](implicit reader: Derivation[ConfigReader[A]]) = new ConfigReader[Map[String, A]] { override def from(cur: ConfigCursor): ConfigReader.Result[Map[String, A]] = { cur.fluent.mapObject { valueCur => reader.value.from(valueCur) } } } implicit def arrayReader[A: ClassTag](implicit reader: Derivation[ConfigReader[A]]) = new ConfigReader[Array[A]] { override def from(cur: ConfigCursor): ConfigReader.Result[Array[A]] = cur.fluent.mapList(reader.value.from).right.map(_.toArray) } } object CollectionReaders extends CollectionReaders
Example 124
Source File: CollectionWriters.scala From pureconfig with Mozilla Public License 2.0 | 5 votes |
package pureconfig import scala.collection.JavaConverters._ import scala.language.higherKinds import com.typesafe.config._ trait CollectionWriters { implicit def optionWriter[A](implicit conv: Derivation[ConfigWriter[A]]): ConfigWriter[Option[A]] = new ConfigWriter[Option[A]] with WritesMissingKeys[Option[A]] { override def to(t: Option[A]): ConfigValue = t match { case Some(v) => conv.value.to(v) case None => ConfigValueFactory.fromAnyRef(null) } def toOpt(t: Option[A]): Option[ConfigValue] = t.map(conv.value.to) } implicit def traversableWriter[A, F[A] <: TraversableOnce[A]]( implicit configConvert: Derivation[ConfigWriter[A]]) = new ConfigWriter[F[A]] { override def to(ts: F[A]): ConfigValue = { ConfigValueFactory.fromIterable(ts.toList.map(configConvert.value.to).asJava) } } implicit def mapWriter[A](implicit configConvert: Derivation[ConfigWriter[A]]) = new ConfigWriter[Map[String, A]] { override def to(keyVals: Map[String, A]): ConfigValue = { ConfigValueFactory.fromMap(keyVals.mapValues(configConvert.value.to).toMap.asJava) } } implicit def arrayWriter[A](implicit writer: Derivation[ConfigWriter[A]]) = new ConfigWriter[Array[A]] { override def to(a: Array[A]): ConfigValue = ConfigValueFactory.fromIterable(a.toList.map(writer.value.to).asJava) } } object CollectionWriters extends CollectionWriters
Example 125
Source File: FoldableTest.scala From study-category-theory with Apache License 2.0 | 5 votes |
package com.github.dnvriend import cats.Foldable import cats.Monoid import cats.instances.all._ import cats.syntax.foldable._ import scala.language.higherKinds class FoldableTest extends TestSpec { def fold[A: Monoid, F[_]](fa: F[A])(implicit foldable: Foldable[F]): A = foldable.fold(fa) it should "fold a List of Int" in { fold(List(1, 2)) shouldBe 3 fold(List.empty[Int]) shouldBe 0 // due to the Monoid[Int].empty } it should "fold a List of String" in { fold(List("a", "b")) shouldBe "ab" fold(List.empty[String]) shouldBe "" // due to the Monoid[String].empty } it should "fold an Option of Int" in { fold(Option(1)) shouldBe 1 fold(Option.empty[Int]) shouldBe 0 // due to the Monoid[Int].empty } it should "combineAll for Int" in { List(1, 2).combineAll shouldBe 3 List.empty[Int].combineAll shouldBe 0 } }
Example 126
Source File: AbstractCompositionTest.scala From study-category-theory with Apache License 2.0 | 5 votes |
package com.github.dnvriend.scalaz import org.scalatest.concurrent.ScalaFutures import org.scalatest.{ FlatSpec, Matchers } import scala.concurrent.Future import scala.concurrent.duration._ import scala.concurrent.ExecutionContext.Implicits.global import scala.language.higherKinds import scalaz._ import Scalaz._ case class StringStats(length: Int, palindrome: Boolean) class AbstractCompositionTest extends FlatSpec with Matchers with ScalaFutures { implicit val pc: PatienceConfig = PatienceConfig(timeout = 30.seconds, interval = 300.millis) def compose[F[_]: Monad, A: Numeric](effectOne: => F[A], effectTwo: => F[A]): F[A] = for { x <- effectOne y <- effectTwo } yield implicitly[Numeric[A]].plus(x, y) it should "compose" in { compose[Option, Long](Option(1), Option(2)) shouldBe Option(3) compose[Future, Long](Future(3), Future(4)).futureValue shouldBe 7 } def stringStats(calcLength: String => Int, isPalindrome: String => Boolean): String => StringStats = for { length <- calcLength palindrome <- isPalindrome } yield StringStats(length, palindrome) }
Example 127
Source File: Arbitrary.scala From hail with MIT License | 5 votes |
package is.hail.check import scala.collection.generic.CanBuildFrom import scala.language.higherKinds object Arbitrary { def apply[T](arbitrary: Gen[T]): Arbitrary[T] = new Arbitrary(arbitrary) implicit def arbBoolean: Arbitrary[Boolean] = new Arbitrary( Gen.oneOf(true, false)) implicit def arbByte: Arbitrary[Byte] = new Arbitrary(Gen.oneOfGen(Gen.oneOf(Byte.MinValue, -1, 0, 1, Byte.MaxValue), Gen { p => p.rng.getRandomGenerator.nextInt().toByte })) implicit def arbInt: Arbitrary[Int] = new Arbitrary( Gen.oneOfGen(Gen.oneOf(Int.MinValue, -1, 0, 1, Int.MaxValue), Gen.choose(-100, 100), Gen { p => p.rng.getRandomGenerator.nextInt() })) implicit def arbLong: Arbitrary[Long] = new Arbitrary( Gen.oneOfGen(Gen.oneOf(Long.MinValue, -1L, 0L, 1L, Long.MaxValue), Gen.choose(-100, 100), Gen { p => p.rng.getRandomGenerator.nextLong() })) implicit def arbFloat: Arbitrary[Float] = new Arbitrary( Gen.oneOfGen(Gen.oneOf(Float.MinValue, -1.0f, -Float.MinPositiveValue, 0.0f, Float.MinPositiveValue, 1.0f, Float.MaxValue), Gen.choose(-100.0f, 100.0f), Gen { p => p.rng.nextUniform(Float.MinValue, Float.MaxValue, true).toFloat })) implicit def arbDouble: Arbitrary[Double] = new Arbitrary( Gen.oneOfGen(Gen.oneOf(Double.MinValue, -1.0, -Double.MinPositiveValue, 0.0, Double.MinPositiveValue, 1.0, Double.MaxValue), Gen.choose(-100.0, 100.0), Gen { p => p.rng.nextUniform(Double.MinValue, Double.MaxValue, true) })) implicit def arbString: Arbitrary[String] = new Arbitrary(Gen.frequency((1, Gen.const("")), (10, Gen { (p: Parameters) => val s = p.rng.getRandomGenerator.nextInt(12) val b = new StringBuilder() for (i <- 0 until s) b += Gen.randomOneOf(p.rng, Gen.printableChars) b.result() }))) implicit def arbBuildableOf[C[_], T](implicit a: Arbitrary[T], cbf: CanBuildFrom[Nothing, T, C[T]]): Arbitrary[C[T]] = Arbitrary(Gen.buildableOf(a.arbitrary)) def arbitrary[T](implicit arb: Arbitrary[T]): Gen[T] = arb.arbitrary } class Arbitrary[T](val arbitrary: Gen[T])
Example 128
Source File: package.scala From CM-Well with Apache License 2.0 | 5 votes |
package cmwell.util import scala.language.higherKinds import scala.collection.generic.CanBuildFrom import scala.collection.mutable import scala.util.{Success, Try} package object exceptions { def trySequence[A, M[X] <: TraversableOnce[X]]( in: M[Try[A]] )(implicit cbf: CanBuildFrom[M[Try[A]], A, M[A]]): Try[M[A]] = { in.foldLeft(Success(cbf(in)): Try[mutable.Builder[A, M[A]]]) { (tr, ta) => { for { r <- tr a <- ta } yield r += a } } .map(_.result()) } def stackTraceToString(t: Throwable): String = { val w = new java.io.StringWriter() val pw = new java.io.PrintWriter(w) t.printStackTrace(pw) val resp = w.toString w.close() pw.close() resp } }
Example 129
Source File: Distribution.scala From pfennig with Apache License 2.0 | 5 votes |
package pfennig import cats.Monad import scala.language.higherKinds sealed trait Distribution[A] { def condition(likelihood: Likelihood[A]): Distribution[A] = Conditional(this, likelihood) def flatMap[B](f: A => Distribution[B]): Distribution[B] = FlatMap(this, f) def map[B](f: A => B): Distribution[B] = FlatMap(this, (a: A) => Pure(f(a))) } final case class Pure[A](get: A) extends Distribution[A] final case class FlatMap[A,B](d: Distribution[A], f: A => Distribution[B]) extends Distribution[B] final case class Primitive[F[_],A](fa: F[A], sampleable: Sampleable[F]) extends Distribution[A] final case class Conditional[A](distribution: Distribution[A], likelihood: Likelihood[A]) extends Distribution[A] object Distribution { implicit object distributionInstances extends Monad[Distribution] with Sampleable[Distribution] { def flatMap[A,B](fa: Distribution[A])(f: A => Distribution[B]): Distribution[B] = fa.flatMap(f) def pure[A](a: A): Distribution[A] = Pure(a) def sample[A](d: Distribution[A])(randomness: Randomness): A = { import Sampleable.ops._ d match { case Pure(a) => a case FlatMap(d, f) => sample(f(sample(d)(randomness)))(randomness) case p: Primitive[f,a] => val fa: f[a] = p.fa implicit val sampleable: Sampleable[f] = p.sampleable fa.sample(randomness) case Conditional(da, l) => throw new Exception("Cannot sample from distributions that have been conditioned.") } } } def bernoulli(weight: Probability): Distribution[Boolean] = Primitive(Random.bernoulli(weight), Random.randomInstances) }
Example 130
Source File: SyncIOMonad.scala From quill with Apache License 2.0 | 5 votes |
package io.getquill.monad import scala.language.higherKinds import scala.collection.compat._ import language.experimental.macros import io.getquill.context.Context import scala.annotation.tailrec import scala.util.Try import io.getquill.{ Query, Action, BatchAction, ActionReturning } trait SyncIOMonad extends IOMonad { this: Context[_, _] => type Result[T] = T def runIO[T](quoted: Quoted[T]): IO[RunQuerySingleResult[T], Effect.Read] = macro IOMonadMacro.runIO def runIO[T](quoted: Quoted[Query[T]]): IO[RunQueryResult[T], Effect.Read] = macro IOMonadMacro.runIO def runIO(quoted: Quoted[Action[_]]): IO[RunActionResult, Effect.Write] = macro IOMonadMacro.runIO def runIO[T](quoted: Quoted[ActionReturning[_, T]]): IO[RunActionReturningResult[T], Effect.Write] = macro IOMonadMacro.runIO def runIO(quoted: Quoted[BatchAction[Action[_]]]): IO[RunBatchActionResult, Effect.Write] = macro IOMonadMacro.runIO def runIO[T](quoted: Quoted[BatchAction[ActionReturning[_, T]]]): IO[RunBatchActionReturningResult[T], Effect.Write] = macro IOMonadMacro.runIO case class Run[T, E <: Effect](f: () => Result[T]) extends IO[T, E] def performIO[T](io: IO[T, _], transactional: Boolean = false): Result[T] = { @tailrec def loop[U](io: IO[U, _]): Result[U] = { def flatten[Y, M[X] <: IterableOnce[X]](seq: Sequence[Y, M, Effect]) = seq.in.iterator.foldLeft(IO.successful(seq.cbfResultToValue.newBuilder)) { (builder, item) => builder.flatMap(b => item.map(b += _)) }.map(_.result()) io match { case FromTry(v) => v.get case Run(f) => f() case seq @ Sequence(_, _) => loop(flatten(seq)) case TransformWith(a, fA) => a match { case FromTry(v) => loop(fA(v)) case Run(r) => loop(fA(Try(r()))) case seq @ Sequence(_, _) => loop(flatten(seq).transformWith(fA)) case TransformWith(b, fB) => loop(b.transformWith(fB(_).transformWith(fA))) case Transactional(io) => loop(fA(Try(performIO(io, transactional = true)))) } case Transactional(io) => performIO(io, transactional = true) } } loop(io) } }
Example 131
Source File: TranslateContext.scala From quill with Apache License 2.0 | 5 votes |
package io.getquill.context import io.getquill.NamingStrategy import io.getquill.idiom.Idiom import scala.annotation.tailrec import scala.language.experimental.macros import scala.language.higherKinds import io.getquill.{ Query, Action, BatchAction } trait TranslateContext extends TranslateContextBase { this: Context[_ <: Idiom, _ <: NamingStrategy] => override type TranslateResult[T] = T override private[getquill] val translateEffect: ContextEffect[TranslateResult] = new ContextEffect[TranslateResult] { override def wrap[T](t: => T): T = t override def push[A, B](result: A)(f: A => B): B = f(result) override def seq[A, B](list: List[A]): List[A] = list } } trait TranslateContextBase { this: Context[_ <: Idiom, _ <: NamingStrategy] => type TranslateResult[T] private[getquill] val translateEffect: ContextEffect[TranslateResult] import translateEffect._ def translate[T](quoted: Quoted[T]): TranslateResult[String] = macro QueryMacro.translateQuery[T] def translate[T](quoted: Quoted[Query[T]]): TranslateResult[String] = macro QueryMacro.translateQuery[T] def translate(quoted: Quoted[Action[_]]): TranslateResult[String] = macro ActionMacro.translateQuery def translate(quoted: Quoted[BatchAction[Action[_]]]): TranslateResult[List[String]] = macro ActionMacro.translateBatchQuery def translate[T](quoted: Quoted[T], prettyPrint: Boolean): TranslateResult[String] = macro QueryMacro.translateQueryPrettyPrint[T] def translate[T](quoted: Quoted[Query[T]], prettyPrint: Boolean): TranslateResult[String] = macro QueryMacro.translateQueryPrettyPrint[T] def translate(quoted: Quoted[Action[_]], prettyPrint: Boolean): TranslateResult[String] = macro ActionMacro.translateQueryPrettyPrint def translate(quoted: Quoted[BatchAction[Action[_]]], prettyPrint: Boolean): TranslateResult[List[String]] = macro ActionMacro.translateBatchQueryPrettyPrint def translateQuery[T](statement: String, prepare: Prepare = identityPrepare, extractor: Extractor[T] = identityExtractor, prettyPrint: Boolean = false): TranslateResult[String] = push(prepareParams(statement, prepare)) { params => val query = if (params.nonEmpty) { params.foldLeft(statement) { case (expanded, param) => expanded.replaceFirst("\\?", param) } } else { statement } if (prettyPrint) idiom.format(query) else query } def translateBatchQuery(groups: List[BatchGroup], prettyPrint: Boolean = false): TranslateResult[List[String]] = seq { groups.flatMap { group => group.prepare.map { prepare => translateQuery(group.string, prepare, prettyPrint = prettyPrint) } } } private[getquill] def prepareParams(statement: String, prepare: Prepare): TranslateResult[Seq[String]] @tailrec final protected def prepareParam(param: Any): String = param match { case None | null => "null" case Some(x) => prepareParam(x) case str: String => s"'$str'" case _ => param.toString } }
Example 132
Source File: Context.scala From quill with Apache License 2.0 | 5 votes |
package io.getquill.context import scala.language.higherKinds import scala.language.experimental.macros import io.getquill.dsl.CoreDsl import io.getquill.util.Messages.fail import java.io.Closeable import scala.util.Try import io.getquill.{ Query, Action, NamingStrategy, BatchAction, ReturnAction, ActionReturning } trait Context[Idiom <: io.getquill.idiom.Idiom, Naming <: NamingStrategy] extends Closeable with CoreDsl { type Result[T] type RunQuerySingleResult[T] type RunQueryResult[T] type RunActionResult type RunActionReturningResult[T] type RunBatchActionResult type RunBatchActionReturningResult[T] type Session type Prepare = PrepareRow => (List[Any], PrepareRow) type Extractor[T] = ResultRow => T case class BatchGroup(string: String, prepare: List[Prepare]) case class BatchGroupReturning(string: String, returningBehavior: ReturnAction, prepare: List[Prepare]) def probe(statement: String): Try[_] def idiom: Idiom def naming: Naming def run[T](quoted: Quoted[T]): Result[RunQuerySingleResult[T]] = macro QueryMacro.runQuerySingle[T] def run[T](quoted: Quoted[Query[T]]): Result[RunQueryResult[T]] = macro QueryMacro.runQuery[T] def prepare[T](quoted: Quoted[Query[T]]): Session => Result[PrepareRow] = macro QueryMacro.prepareQuery[T] def run(quoted: Quoted[Action[_]]): Result[RunActionResult] = macro ActionMacro.runAction def run[T](quoted: Quoted[ActionReturning[_, T]]): Result[RunActionReturningResult[T]] = macro ActionMacro.runActionReturning[T] def run(quoted: Quoted[BatchAction[Action[_]]]): Result[RunBatchActionResult] = macro ActionMacro.runBatchAction def run[T](quoted: Quoted[BatchAction[ActionReturning[_, T]]]): Result[RunBatchActionReturningResult[T]] = macro ActionMacro.runBatchActionReturning[T] def prepare(quoted: Quoted[Action[_]]): Session => Result[PrepareRow] = macro ActionMacro.prepareAction def prepare(quoted: Quoted[BatchAction[Action[_]]]): Session => Result[List[PrepareRow]] = macro ActionMacro.prepareBatchAction protected val identityPrepare: Prepare = (Nil, _) protected val identityExtractor = identity[ResultRow] _ protected def handleSingleResult[T](list: List[T]) = list match { case value :: Nil => value case other => fail(s"Expected a single result but got $other") } }
Example 133
Source File: ArrayEncoding.scala From quill with Apache License 2.0 | 5 votes |
package io.getquill.context.sql.encoding import java.time.LocalDate import java.util.Date import io.getquill.context.sql.SqlContext import scala.collection.compat._ import scala.language.higherKinds trait ArrayEncoding { self: SqlContext[_, _] => type CBF[T, Col] = Factory[T, Col] implicit def arrayStringEncoder[Col <: Seq[String]]: Encoder[Col] implicit def arrayBigDecimalEncoder[Col <: Seq[BigDecimal]]: Encoder[Col] implicit def arrayBooleanEncoder[Col <: Seq[Boolean]]: Encoder[Col] implicit def arrayByteEncoder[Col <: Seq[Byte]]: Encoder[Col] implicit def arrayShortEncoder[Col <: Seq[Short]]: Encoder[Col] implicit def arrayIntEncoder[Col <: Seq[Int]]: Encoder[Col] implicit def arrayLongEncoder[Col <: Seq[Long]]: Encoder[Col] implicit def arrayFloatEncoder[Col <: Seq[Float]]: Encoder[Col] implicit def arrayDoubleEncoder[Col <: Seq[Double]]: Encoder[Col] implicit def arrayDateEncoder[Col <: Seq[Date]]: Encoder[Col] implicit def arrayLocalDateEncoder[Col <: Seq[LocalDate]]: Encoder[Col] implicit def arrayStringDecoder[Col <: Seq[String]](implicit bf: CBF[String, Col]): Decoder[Col] implicit def arrayBigDecimalDecoder[Col <: Seq[BigDecimal]](implicit bf: CBF[BigDecimal, Col]): Decoder[Col] implicit def arrayBooleanDecoder[Col <: Seq[Boolean]](implicit bf: CBF[Boolean, Col]): Decoder[Col] implicit def arrayByteDecoder[Col <: Seq[Byte]](implicit bf: CBF[Byte, Col]): Decoder[Col] implicit def arrayShortDecoder[Col <: Seq[Short]](implicit bf: CBF[Short, Col]): Decoder[Col] implicit def arrayIntDecoder[Col <: Seq[Int]](implicit bf: CBF[Int, Col]): Decoder[Col] implicit def arrayLongDecoder[Col <: Seq[Long]](implicit bf: CBF[Long, Col]): Decoder[Col] implicit def arrayFloatDecoder[Col <: Seq[Float]](implicit bf: CBF[Float, Col]): Decoder[Col] implicit def arrayDoubleDecoder[Col <: Seq[Double]](implicit bf: CBF[Double, Col]): Decoder[Col] implicit def arrayDateDecoder[Col <: Seq[Date]](implicit bf: CBF[Date, Col]): Decoder[Col] implicit def arrayLocalDateDecoder[Col <: Seq[LocalDate]](implicit bf: CBF[LocalDate, Col]): Decoder[Col] implicit def arrayMappedEncoder[I, O, Col[X] <: Seq[X]]( implicit mapped: MappedEncoding[I, O], e: Encoder[Seq[O]] ): Encoder[Col[I]] = { mappedEncoder[Col[I], Seq[O]](MappedEncoding((col: Col[I]) => col.map(mapped.f)), e) } implicit def arrayMappedDecoder[I, O, Col[X] <: Seq[X]]( implicit mapped: MappedEncoding[I, O], d: Decoder[Seq[I]], bf: Factory[O, Col[O]] ): Decoder[Col[O]] = { mappedDecoder[Seq[I], Col[O]](MappedEncoding((col: Seq[I]) => col.foldLeft(bf.newBuilder)((b, x) => b += mapped.f(x)).result), d) } }
Example 134
Source File: package.scala From diffx with Apache License 2.0 | 5 votes |
package com.softwaremill import acyclic.skipped import scala.annotation.compileTimeOnly import scala.collection.TraversableLike import scala.collection.generic.CanBuildFrom import scala.language.experimental.macros import scala.language.higherKinds import com.softwaremill.diffx.DiffxSupport._ package object diffx extends DiffxSupport { implicit def traversableDiffxFunctor[F[_], A](implicit cbf: CanBuildFrom[F[A], A, F[A]], ev: F[A] => TraversableLike[A, F[A]] ): DiffxFunctor[F, A] = new DiffxFunctor[F, A] {} trait DiffxMapAtFunctor[F[_, _], K, T] { @compileTimeOnly(canOnlyBeUsedInsideIgnore("each")) def each(fa: F[K, T])(f: T => T): F[K, T] = sys.error("") } implicit def mapDiffxFunctor[M[KT, TT] <: Map[KT, TT], K, T](implicit cbf: CanBuildFrom[M[K, T], (K, T), M[K, T]] ): DiffxMapAtFunctor[M, K, T] = new DiffxMapAtFunctor[M, K, T] {} implicit class DiffxEachMap[F[_, _], K, T](t: F[K, T])(implicit f: DiffxMapAtFunctor[F, K, T]) { @compileTimeOnly(canOnlyBeUsedInsideIgnore("each")) def each: T = sys.error("") } }
Example 135
Source File: EitherTValues.scala From guardrail with MIT License | 5 votes |
package tests.scalatest import cats.Functor import cats.data.EitherT import org.scalactic.source import org.scalatest._ import org.scalatest.exceptions.{ StackDepthException, TestFailedException } import scala.language.higherKinds import scala.language.implicitConversions trait EitherTValues { implicit def convertEitherTToValuable[F[_]: Functor, L, R](eitherT: EitherT[F, L, R]) = new EitherTValuable(eitherT) class EitherTValuable[F[_]: Functor, L, R](eitherT: EitherT[F, L, R]) { def leftValue(implicit pos: source.Position): F[L] = eitherT.fold(identity, { _ => throw new TestFailedException((_: StackDepthException) => Option.empty[String], Option.empty[Throwable], pos) }) def rightValue(implicit pos: source.Position): F[R] = eitherT.fold({ _ => throw new TestFailedException((_: StackDepthException) => Option.empty[String], Option.empty[Throwable], pos) }, identity) } }
Example 136
Source File: EitherTValues.scala From guardrail with MIT License | 5 votes |
package tests.scalatest import cats.Functor import cats.data.EitherT import org.scalactic.source import org.scalatest._ import org.scalatest.exceptions.{ StackDepthException, TestFailedException } import scala.language.higherKinds import scala.language.implicitConversions trait EitherTValues { implicit def convertEitherTToValuable[F[_]: Functor, L, R](eitherT: EitherT[F, L, R]) = new EitherTValuable(eitherT) class EitherTValuable[F[_]: Functor, L, R](eitherT: EitherT[F, L, R]) { def leftValue(implicit pos: source.Position): F[L] = eitherT.fold(identity, { _ => throw new TestFailedException((_: StackDepthException) => Option.empty[String], Option.empty[Throwable], pos) }) def rightValue(implicit pos: source.Position): F[R] = eitherT.fold({ _ => throw new TestFailedException((_: StackDepthException) => Option.empty[String], Option.empty[Throwable], pos) }, identity) } }
Example 137
Source File: EitherTValues.scala From guardrail with MIT License | 5 votes |
package tests.scalatest import cats.Functor import cats.data.EitherT import org.scalactic.source import org.scalatest._ import org.scalatest.exceptions.{ StackDepthException, TestFailedException } import scala.language.higherKinds import scala.language.implicitConversions trait EitherTValues { implicit def convertEitherTToValuable[F[_]: Functor, L, R](eitherT: EitherT[F, L, R]) = new EitherTValuable(eitherT) class EitherTValuable[F[_]: Functor, L, R](eitherT: EitherT[F, L, R]) { def leftValue(implicit pos: source.Position): F[L] = eitherT.fold(identity, { _ => throw new TestFailedException((_: StackDepthException) => Option.empty[String], Option.empty[Throwable], pos) }) def rightValue(implicit pos: source.Position): F[R] = eitherT.fold({ _ => throw new TestFailedException((_: StackDepthException) => Option.empty[String], Option.empty[Throwable], pos) }, identity) } }
Example 138
Source File: CatsEffect.scala From cats-effect-testing with Apache License 2.0 | 5 votes |
package cats.effect.testing.specs2 import cats.effect.{Effect, Resource, Sync} import cats.effect.syntax.effect._ import org.specs2.execute.{AsResult, Failure, Result} import scala.concurrent.duration._ import scala.language.higherKinds trait CatsEffect { protected val Timeout: Duration = 10.seconds implicit def effectAsResult[F[_]: Effect, R](implicit R: AsResult[R]): AsResult[F[R]] = new AsResult[F[R]] { def asResult(t: => F[R]): Result = t.toIO.unsafeRunTimed(Timeout) .map(R.asResult(_)) .getOrElse(Failure(s"expectation timed out after $Timeout")) } implicit def resourceAsResult[F[_]: Effect, R](implicit R: AsResult[R]): AsResult[Resource[F,R]] = new AsResult[Resource[F,R]]{ def asResult(t: => Resource[F, R]): Result = t.use(r => Sync[F].delay(R.asResult(r))) .toIO .unsafeRunTimed(Timeout) .getOrElse(Failure(s"expectation timed out after $Timeout")) } }
Example 139
Source File: EntryFilter.scala From hazelcast-scala with Apache License 2.0 | 5 votes |
package com.hazelcast.Scala import scala.language.{ higherKinds } import com.hazelcast.query.Predicate import collection.mutable.Map sealed trait EntryFilter[K, V] { type EV type M[R] } final case class OnEntries[K, V](predicate: Predicate[_, _] = null) extends EntryFilter[K, V] { type EV = V type M[R] = Map[K, R] } final case class OnValues[K, V](include: V => Boolean) extends EntryFilter[K, V] { type EV = V type M[R] = Map[K, R] } final case class OnKeys[K, V](keys: collection.Set[K]) extends EntryFilter[K, V] { type EV = V type M[R] = Map[K, R] } object OnKeys { def apply[K, V](key1: K, key2: K, keyn: K*) = new OnKeys[K, V](keyn.toSet + key1 + key2) } final case class OnKey[K, V](key: K) extends EntryFilter[K, V] { type EV = Option[V] type M[R] = R }
Example 140
Source File: GithubIssue180.scala From avro4s with Apache License 2.0 | 5 votes |
package com.sksamuel.avro4s.github import com.sksamuel.avro4s.github.SampleProtocol.SubPart1.InnerEnum import com.sksamuel.avro4s.{AvroSchema, FromRecord, ToRecord} import org.scalatest.funspec.AnyFunSpec import org.scalatest.matchers.should.Matchers import scala.language.higherKinds object TopEnum extends Enumeration { type TopEnumVal = Value val v1, v2 = Value } case class WithTopEnum(topEnum: TopEnum.TopEnumVal) object SampleProtocol { object SubPart1 { object InnerEnum extends Enumeration { type InnerEnum = Value val vv1, vv2 = Value } } } case class WithInnerEnum(ie: InnerEnum.InnerEnum) class Githu4bIssue180 extends AnyFunSpec with Matchers { describe("SchemaFor : FromRecord : ToRecord") { describe("with top level scala Enumerations") { val withTopEnum = WithTopEnum(TopEnum.v1) it("should be able to compile `FromRecord`") { FromRecord[WithTopEnum] shouldNot be(null) } it("should be able to compile `ToRecord`") { ToRecord[WithTopEnum] shouldNot be(null) } it("should be able to compile `SchemaFor`") { AvroSchema[WithTopEnum] shouldNot be(null) } } describe("with non-top level scala Enumerations") { val withInnerEnum = WithInnerEnum(InnerEnum.vv1) it("should be able to compile `FromRecord`") { FromRecord[WithInnerEnum] shouldNot be(null) } it("should be able to compile `ToRecord`") { ToRecord[WithInnerEnum] shouldNot be(null) } it("should be able to compile `SchemaFor`") { AvroSchema[WithInnerEnum] shouldNot be(null) } } } }
Example 141
Source File: GithubIssue281.scala From avro4s with Apache License 2.0 | 5 votes |
package com.sksamuel.avro4s.github import com.sksamuel.avro4s.AvroSchema import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers import scala.language.higherKinds sealed trait InnerTrait case class InnerTraitConcrete(v: Int) extends InnerTrait case class InnerTraitConcrete2(v: Int) extends InnerTrait case class Inner(t: InnerTrait) case class Outer(inners: Seq[Inner]) class GithubIssue281 extends AnyFunSuite with Matchers { test("Avro Schema for a sealed trait in a subobject #281") { AvroSchema[Outer].toString(true) shouldBe """{ | "type" : "record", | "name" : "Outer", | "namespace" : "com.sksamuel.avro4s.github", | "fields" : [ { | "name" : "inners", | "type" : { | "type" : "array", | "items" : { | "type" : "record", | "name" : "Inner", | "fields" : [ { | "name" : "t", | "type" : [ { | "type" : "record", | "name" : "InnerTraitConcrete", | "fields" : [ { | "name" : "v", | "type" : "int" | } ] | }, { | "type" : "record", | "name" : "InnerTraitConcrete2", | "fields" : [ { | "name" : "v", | "type" : "int" | } ] | } ] | } ] | } | } | } ] |}""".stripMargin } }
Example 142
Source File: ByteArrayDecoderTest.scala From avro4s with Apache License 2.0 | 5 votes |
package com.sksamuel.avro4s.record.decoder import java.nio.ByteBuffer import com.sksamuel.avro4s.{AvroSchema, Decoder} import org.apache.avro.generic.GenericData import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers import scala.language.higherKinds class ByteArrayDecoderTest extends AnyFunSuite with Matchers { case class ArrayTest(z: Array[Byte]) case class ByteBufferTest(z: ByteBuffer) case class VectorTest(z: Vector[Byte]) case class SeqTest(z: Array[Byte]) case class ListTest(z: Array[Byte]) test("decode byte arrays") { val schema = AvroSchema[ArrayTest] val record = new GenericData.Record(schema) record.put("z", ByteBuffer.wrap(Array[Byte](1, 4, 9))) Decoder[ArrayTest].decode(record).z.toList shouldBe List[Byte](1, 4, 9) } test("decode bytebuffers to array") { val schema = AvroSchema[ArrayTest] val record = new GenericData.Record(schema) record.put("z", ByteBuffer.wrap(Array[Byte](1, 4, 9))) Decoder[ArrayTest].decode(record).z.toList shouldBe List[Byte](1, 4, 9) } test("decode byte vectors") { val schema = AvroSchema[VectorTest] val record = new GenericData.Record(schema) record.put("z", ByteBuffer.wrap(Array[Byte](1, 4, 9))) Decoder[VectorTest].decode(record).z shouldBe Vector[Byte](1, 4, 9) } test("decode byte lists") { val schema = AvroSchema[ListTest] val record = new GenericData.Record(schema) record.put("z", ByteBuffer.wrap(Array[Byte](1, 4, 9))) Decoder[ListTest].decode(record).z shouldBe List[Byte](1, 4, 9) } test("decode byte seqs") { val schema = AvroSchema[SeqTest] val record = new GenericData.Record(schema) record.put("z", ByteBuffer.wrap(Array[Byte](1, 4, 9))) Decoder[SeqTest].decode(record).z shouldBe Seq[Byte](1, 4, 9) } test("decode top level byte arrays") { Decoder[Array[Byte]].decode(ByteBuffer.wrap(Array[Byte](1, 4, 9))).toList shouldBe List[Byte](1, 4, 9) } test("decode array to bytebuffers") { val schema = AvroSchema[ByteBufferTest] val record = new GenericData.Record(schema) record.put("z", Array[Byte](1, 4, 9)) Decoder[ByteBufferTest].decode(record).z.array().toList shouldBe List[Byte](1, 4, 9) } test("decode bytebuffers") { val schema = AvroSchema[ByteBufferTest] val record = new GenericData.Record(schema) record.put("z", ByteBuffer.wrap(Array[Byte](1, 4, 9))) Decoder[ByteBufferTest].decode(record).z.array().toList shouldBe List[Byte](1, 4, 9) } test("decode top level ByteBuffers") { Decoder[ByteBuffer].decode(ByteBuffer.wrap(Array[Byte](1, 4, 9))).array().toList shouldBe List[Byte](1, 4, 9) } }
Example 143
Source File: Sequencing.scala From futiles with Apache License 2.0 | 5 votes |
package markatta.futiles import scala.collection.BuildFrom import scala.concurrent.{ExecutionContext, Future} import scala.language.higherKinds import scala.util.Try def sequenceTries[A, M[X] <: IterableOnce[X]](fas: M[Future[A]])( implicit ec: ExecutionContext, cbf: BuildFrom[M[Future[A]], Try[A], M[Try[A]]] ): Future[M[Try[A]]] = { val fts = fas.iterator.foldLeft(Future.successful(cbf.newBuilder(fas))) { (facc, fa) => for { acc <- facc ta <- Lifting.liftTry(fa) } yield acc += ta } fts.map(_.result()) } }
Example 144
Source File: Sequencing.scala From futiles with Apache License 2.0 | 5 votes |
package markatta.futiles import scala.collection.generic.CanBuildFrom import scala.concurrent.{ExecutionContext, Future} import scala.language.higherKinds import scala.util.Try def sequenceTries[A, M[X] <: TraversableOnce[X]]( fas: M[Future[A]] )( implicit ec: ExecutionContext, cbf: CanBuildFrom[M[Future[A]], Try[A], M[Try[A]]] ): Future[M[Try[A]]] = { val fts = fas.foldLeft(Future.successful(cbf())) { (facc, fa) => for { acc <- facc ta <- Lifting.liftTry(fa) } yield acc += ta } fts.map(_.result()) } }
Example 145
Source File: CatsAsyncHandler.scala From pulsar4s with Apache License 2.0 | 5 votes |
package com.sksamuel.pulsar4s.cats import java.util.concurrent.CompletableFuture import java.util.function.BiConsumer import cats.implicits._ import cats.effect._ import com.sksamuel.pulsar4s.{AsyncHandler, ConsumerMessage, DefaultProducer, MessageId, Producer} import org.apache.pulsar.client.api import org.apache.pulsar.client.api.{ProducerBuilder, Reader, TypedMessageBuilder} import scala.language.higherKinds import scala.util.{Failure, Success, Try} object CatsAsyncHandler extends CatsAsyncHandlerLowPriority { implicit def handler: AsyncHandler[IO] = asyncHandlerForCatsEffectAsync[IO] } trait CatsAsyncHandlerLowPriority { object CompletableFutureConverters { implicit class CompletableOps[T](f: => CompletableFuture[T]) { def toF[F[_]: Async]: F[T] = Async[F].async[T] { k => f.whenCompleteAsync(new BiConsumer[T, Throwable] { override def accept(t: T, e: Throwable): Unit = { if (e != null) k.apply(Left(e)) else k.apply(Right(t)) } }) } } } implicit def asyncHandlerForCatsEffectAsync[F[_]: Async]: AsyncHandler[F] = new AsyncHandler[F] { import CompletableFutureConverters._ override def failed(e: Throwable): F[Nothing] = Async[F].raiseError(e) override def createProducer[T](builder: ProducerBuilder[T]): F[Producer[T]] = builder.createAsync().toF[F].map(new DefaultProducer(_)) override def send[T](t: T, producer: api.Producer[T]): F[MessageId] = producer.sendAsync(t).toF[F].map(MessageId.fromJava) override def receive[T](consumer: api.Consumer[T]): F[ConsumerMessage[T]] = consumer.receiveAsync().toF[F].map(ConsumerMessage.fromJava) override def unsubscribeAsync(consumer: api.Consumer[_]): F[Unit] = consumer.unsubscribeAsync().toF[F].void override def getLastMessageId[T](consumer: api.Consumer[T]): F[MessageId] = consumer.getLastMessageIdAsync().toF[F].map(MessageId.fromJava) override def close(producer: api.Producer[_]): F[Unit] = producer.closeAsync().toF[F].void override def close(consumer: api.Consumer[_]): F[Unit] = consumer.closeAsync().toF[F].void override def seekAsync(consumer: api.Consumer[_], messageId: MessageId): F[Unit] = consumer.seekAsync(messageId).toF[F].void override def seekAsync(reader: api.Reader[_], messageId: MessageId): F[Unit] = reader.seekAsync(messageId).toF[F].void override def seekAsync(reader: api.Reader[_], timestamp: Long): F[Unit] = reader.seekAsync(timestamp).toF[F].void override def transform[A, B](t: F[A])(fn: A => Try[B]): F[B] = t.flatMap { a => fn(a) match { case Success(b) => Async[F].pure(b) case Failure(e) => Async[F].raiseError(e) } } override def acknowledgeAsync[T](consumer: api.Consumer[T], messageId: MessageId): F[Unit] = consumer.acknowledgeAsync(messageId).toF[F].void override def acknowledgeCumulativeAsync[T](consumer: api.Consumer[T], messageId: MessageId): F[Unit] = consumer.acknowledgeCumulativeAsync(messageId).toF[F].void override def negativeAcknowledgeAsync[T](consumer: api.Consumer[T], messageId: MessageId): F[Unit] = Async[F].delay { consumer.negativeAcknowledge(messageId) } override def close(reader: Reader[_]): F[Unit] = reader.closeAsync().toF[F].void override def flush(producer: api.Producer[_]): F[Unit] = producer.flushAsync().toF[F].void override def nextAsync[T](reader: Reader[T]): F[ConsumerMessage[T]] = reader.readNextAsync().toF[F].map(ConsumerMessage.fromJava) override def send[T](builder: TypedMessageBuilder[T]): F[MessageId] = builder.sendAsync().toF[F].map(MessageId.fromJava) } }
Example 146
Source File: SQSConsumerBuilder.scala From fs2-aws with MIT License | 5 votes |
package fs2.aws.sqs import cats.effect.Effect import com.amazon.sqs.javamessaging.{ ProviderConfiguration, SQSConnection, SQSConnectionFactory } import com.amazonaws.services.sqs.AmazonSQSClientBuilder import eu.timepit.refined.auto._ import javax.jms.{ MessageListener, Session } import scala.language.higherKinds class SQSConsumerBuilder[F[_]](val sqsConfig: SqsConfig, val listener: MessageListener)( implicit F: Effect[F] ) extends ConsumerBuilder[F] { val start: F[SQSConsumer] = { F.delay { new SQSConsumer { override val callback: MessageListener = listener val connectionFactory = new SQSConnectionFactory( new ProviderConfiguration(), AmazonSQSClientBuilder.defaultClient() ) override val connection: SQSConnection = connectionFactory.createConnection override def startConsumer(): Unit = { val session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE) val cons = session.createConsumer(session.createQueue(sqsConfig.queueName)) cons.setMessageListener(callback) connection.start() } override def shutdown(): Unit = connection.stop() } } } } object SQSConsumerBuilder { def apply[F[_]](sqsConfig: SqsConfig, listener: MessageListener)( implicit F: Effect[F] ): SQSConsumerBuilder[F] = new SQSConsumerBuilder[F](sqsConfig, listener) }
Example 147
Source File: XCompat.scala From boopickle with Apache License 2.0 | 5 votes |
package boopickle import boopickle.Constants.NullRef import scala.collection.Factory import scala.language.higherKinds trait XCompatImplicitPicklers { this: PicklerHelper => implicit def mapPickler[T: P, S: P, V[_, _] <: scala.collection.Map[_, _]]( implicit cbf: Factory[(T, S), V[T, S]]): P[V[T, S]] = BasicPicklers.MapPickler[T, S, V] implicit def iterablePickler[T: P, V[_] <: Iterable[_]](implicit cbf: Factory[T, V[T]]): P[V[T]] = BasicPicklers.IterablePickler[T, V] } trait XCompatPicklers { this: PicklerHelper => def MapPickler[T: P, S: P, V[_, _] <: scala.collection.Map[_, _]](implicit cbf: Factory[(T, S), V[T, S]]): P[V[T, S]] = new P[V[T, S]] { override def pickle(map: V[T, S])(implicit state: PickleState): Unit = { if (map == null) { state.enc.writeInt(NullRef) } else { // encode length state.enc.writeInt(map.size) // encode contents as a sequence val kPickler = implicitly[P[T]] val vPickler = implicitly[P[S]] map.asInstanceOf[scala.collection.Map[T, S]].foreach { kv => kPickler.pickle(kv._1)(state) vPickler.pickle(kv._2)(state) } } } override def unpickle(implicit state: UnpickleState): V[T, S] = { state.dec.readInt match { case NullRef => null.asInstanceOf[V[T, S]] case 0 => // empty map val res = cbf.newBuilder.result res case idx if idx < 0 => state.identityFor[V[T, S]](-idx) case len => val b = cbf.newBuilder b.sizeHint(len) val kPickler = implicitly[P[T]] val vPickler = implicitly[P[S]] var i = 0 while (i < len) { b += kPickler.unpickle(state) -> vPickler.unpickle(state) i += 1 } val res = b.result res } } } }
Example 148
Source File: XCompat.scala From boopickle with Apache License 2.0 | 5 votes |
package boopickle import boopickle.Constants.NullRef import collection.generic.CanBuildFrom import scala.collection.generic.CanBuildFrom import scala.language.higherKinds trait XCompatImplicitPicklers { this: PicklerHelper => implicit def mapPickler[T: P, S: P, V[_, _] <: scala.collection.Map[_, _]]( implicit cbf: CanBuildFrom[Nothing, (T, S), V[T, S]]): P[V[T, S]] = BasicPicklers.MapPickler[T, S, V] implicit def iterablePickler[T: P, V[_] <: Iterable[_]](implicit cbf: CanBuildFrom[Nothing, T, V[T]]): P[V[T]] = BasicPicklers.IterablePickler[T, V] } trait XCompatPicklers { this: PicklerHelper => def MapPickler[T: P, S: P, V[_, _] <: scala.collection.Map[_, _]]( implicit cbf: CanBuildFrom[Nothing, (T, S), V[T, S]]): P[V[T, S]] = new P[V[T, S]] { override def pickle(map: V[T, S])(implicit state: PickleState): Unit = { if (map == null) { state.enc.writeInt(NullRef) } else { // encode length state.enc.writeInt(map.size) // encode contents as a sequence val kPickler = implicitly[P[T]] val vPickler = implicitly[P[S]] map.asInstanceOf[scala.collection.Map[T, S]].foreach { kv => kPickler.pickle(kv._1)(state) vPickler.pickle(kv._2)(state) } } } override def unpickle(implicit state: UnpickleState): V[T, S] = { state.dec.readInt match { case NullRef => null.asInstanceOf[V[T, S]] case 0 => // empty map val res = cbf().result() res case idx if idx < 0 => state.identityFor[V[T, S]](-idx) case len => val b = cbf() b.sizeHint(len) val kPickler = implicitly[P[T]] val vPickler = implicitly[P[S]] var i = 0 while (i < len) { b += kPickler.unpickle(state) -> vPickler.unpickle(state) i += 1 } val res = b.result() res } } } }
Example 149
Source File: AsyncHttpClientFs2Backend.scala From sttp with Apache License 2.0 | 5 votes |
package sttp.client.asynchttpclient.fs2 import java.io.File import java.nio.ByteBuffer import cats.effect._ import cats.effect.implicits._ import cats.implicits._ import fs2.{Chunk, Stream} import fs2.interop.reactivestreams._ import io.netty.buffer.{ByteBuf, Unpooled} import org.asynchttpclient.{Request => _, Response => _, _} import org.reactivestreams.Publisher import sttp.client.asynchttpclient.{AsyncHttpClientBackend, WebSocketHandler} import sttp.client.impl.cats.CatsMonadAsyncError import sttp.client.internal._ import sttp.client.testing.SttpBackendStub import sttp.client.ws.WebSocketResponse import sttp.client.{FollowRedirectsBackend, SttpBackend, SttpBackendOptions, _} import scala.concurrent.ExecutionContext import scala.language.higherKinds class AsyncHttpClientFs2Backend[F[_]: ConcurrentEffect: ContextShift] private ( asyncHttpClient: AsyncHttpClient, closeClient: Boolean, customizeRequest: BoundRequestBuilder => BoundRequestBuilder ) extends AsyncHttpClientBackend[F, Stream[F, Byte]]( asyncHttpClient, new CatsMonadAsyncError, closeClient, customizeRequest ) { override def send[T](r: Request[T, Stream[F, Byte]]): F[Response[T]] = { super.send(r).guarantee(implicitly[ContextShift[F]].shift) } override def openWebsocket[T, WS_RESULT]( r: Request[T, Stream[F, Byte]], handler: WebSocketHandler[WS_RESULT] ): F[WebSocketResponse[WS_RESULT]] = super.openWebsocket(r, handler).guarantee(ContextShift[F].shift) override protected def streamBodyToPublisher(s: Stream[F, Byte]): Publisher[ByteBuf] = s.chunks.map(c => Unpooled.wrappedBuffer(c.toArray)).toUnicastPublisher override protected def publisherToStreamBody(p: Publisher[ByteBuffer]): Stream[F, Byte] = p.toStream[F].flatMap(buf => Stream.chunk(Chunk.byteBuffer(buf))) override protected def publisherToBytes(p: Publisher[ByteBuffer]): F[Array[Byte]] = { p.toStream[F] .compile .fold(ByteBuffer.allocate(0))(concatByteBuffers) .map(_.array()) } override protected def publisherToFile(p: Publisher[ByteBuffer], f: File): F[Unit] = { p.toStream[F] .flatMap(b => Stream.emits(b.array())) .through(fs2.io.file.writeAll(f.toPath, Blocker.liftExecutionContext(ExecutionContext.global))) .compile .drain } } object AsyncHttpClientFs2Backend { private def apply[F[_]: ConcurrentEffect: ContextShift]( asyncHttpClient: AsyncHttpClient, closeClient: Boolean, customizeRequest: BoundRequestBuilder => BoundRequestBuilder ): SttpBackend[F, Stream[F, Byte], WebSocketHandler] = new FollowRedirectsBackend(new AsyncHttpClientFs2Backend(asyncHttpClient, closeClient, customizeRequest)) def apply[F[_]: ConcurrentEffect: ContextShift]( options: SttpBackendOptions = SttpBackendOptions.Default, customizeRequest: BoundRequestBuilder => BoundRequestBuilder = identity ): F[SttpBackend[F, Stream[F, Byte], WebSocketHandler]] = implicitly[Sync[F]] .delay(apply[F](AsyncHttpClientBackend.defaultClient(options), closeClient = true, customizeRequest)) def stub[F[_]: Concurrent]: SttpBackendStub[F, Stream[F, ByteBuffer], WebSocketHandler] = SttpBackendStub(new CatsMonadAsyncError()) }
Example 150
Source File: implicits.scala From sttp with Apache License 2.0 | 5 votes |
package sttp.client.impl.scalaz import scalaz.~> import sttp.client.monad.MonadError import sttp.client.ws.WebSocketResponse import sttp.client.{Request, Response, SttpBackend} import scala.language.higherKinds object implicits extends ScalazImplicits trait ScalazImplicits { implicit final def sttpBackendToScalazMappableSttpBackend[F[_], S, WS_HANDLER[_]]( sttpBackend: SttpBackend[F, S, WS_HANDLER] ): MappableSttpBackend[F, S, WS_HANDLER] = new MappableSttpBackend(sttpBackend) } final class MappableSttpBackend[F[_], S, WS_HANDLER[_]] private[scalaz] ( private val sttpBackend: SttpBackend[F, S, WS_HANDLER] ) extends AnyVal { def mapK[G[_]: MonadError](f: F ~> G): SttpBackend[G, S, WS_HANDLER] = new MappedKSttpBackend(sttpBackend, f, implicitly) } private[scalaz] final class MappedKSttpBackend[F[_], -S, WS_HANDLER[_], G[_]]( wrapped: SttpBackend[F, S, WS_HANDLER], mapping: F ~> G, val responseMonad: MonadError[G] ) extends SttpBackend[G, S, WS_HANDLER] { def send[T](request: Request[T, S]): G[Response[T]] = mapping(wrapped.send(request)) override def openWebsocket[T, WS_RESULT]( request: Request[T, S], handler: WS_HANDLER[WS_RESULT] ): G[WebSocketResponse[WS_RESULT]] = mapping(wrapped.openWebsocket(request, handler)) def close(): G[Unit] = mapping(wrapped.close()) }
Example 151
Source File: Fs2AsyncQueue.scala From sttp with Apache License 2.0 | 5 votes |
package sttp.client.impl.fs2 import cats.effect.{Effect, IO} import fs2.concurrent.InspectableQueue import sttp.client.ws.internal.AsyncQueue import sttp.model.ws.WebSocketBufferFull import scala.language.higherKinds class Fs2AsyncQueue[F[_], A](queue: InspectableQueue[F, A])(implicit F: Effect[F]) extends AsyncQueue[F, A] { override def offer(t: A): Unit = { F.toIO(queue.offer1(t)) .flatMap { case true => IO.unit case false => IO.raiseError(new WebSocketBufferFull()) } .unsafeRunSync() } override def poll: F[A] = queue.dequeue1 }
Example 152
Source File: implicits.scala From sttp with Apache License 2.0 | 5 votes |
package sttp.client.impl.cats import cats.effect.Concurrent import cats.~> import sttp.client.monad.{MonadAsyncError, MonadError} import sttp.client.ws.WebSocketResponse import sttp.client.{Request, Response, SttpBackend} import scala.language.higherKinds object implicits extends CatsImplicits trait CatsImplicits extends LowLevelCatsImplicits { implicit final def sttpBackendToCatsMappableSttpBackend[R[_], S, WS_HANDLER[_]]( sttpBackend: SttpBackend[R, S, WS_HANDLER] ): MappableSttpBackend[R, S, WS_HANDLER] = new MappableSttpBackend(sttpBackend) implicit final def asyncMonadError[F[_]: Concurrent]: MonadAsyncError[F] = new CatsMonadAsyncError[F] } trait LowLevelCatsImplicits { implicit final def catsMonadError[F[_]](implicit E: cats.MonadError[F, Throwable]): MonadError[F] = new CatsMonadError[F] } final class MappableSttpBackend[F[_], S, WS_HANDLER[_]] private[cats] ( private val sttpBackend: SttpBackend[F, S, WS_HANDLER] ) extends AnyVal { def mapK[G[_]: MonadError](f: F ~> G): SttpBackend[G, S, WS_HANDLER] = new MappedKSttpBackend(sttpBackend, f, implicitly) } private[cats] final class MappedKSttpBackend[F[_], -S, WS_HANDLER[_], G[_]]( wrapped: SttpBackend[F, S, WS_HANDLER], mapping: F ~> G, val responseMonad: MonadError[G] ) extends SttpBackend[G, S, WS_HANDLER] { def send[T](request: Request[T, S]): G[Response[T]] = mapping(wrapped.send(request)) override def openWebsocket[T, WS_RESULT]( request: Request[T, S], handler: WS_HANDLER[WS_RESULT] ): G[WebSocketResponse[WS_RESULT]] = mapping(wrapped.openWebsocket(request, handler)) def close(): G[Unit] = mapping(wrapped.close()) }
Example 153
Source File: DigestAuthenticationBackend.scala From sttp with Apache License 2.0 | 5 votes |
package sttp.client import sttp.client.DigestAuthenticationBackend._ import sttp.client.internal.DigestAuthenticator import sttp.client.internal.DigestAuthenticator.DigestAuthData import sttp.client.monad.MonadError import sttp.client.monad.syntax._ import sttp.client.ws.WebSocketResponse import sttp.model.Header import scala.language.higherKinds class DigestAuthenticationBackend[F[_], S, WS_HANDLER[_]]( delegate: SttpBackend[F, S, WS_HANDLER], clientNonceGenerator: () => String = DigestAuthenticator.defaultClientNonceGenerator ) extends SttpBackend[F, S, WS_HANDLER] { private implicit val m: MonadError[F] = responseMonad override def send[T](request: Request[T, S]): F[Response[T]] = { delegate .send(request) .flatMap { firstResponse => handleResponse(request, firstResponse, ProxyDigestAuthTag, DigestAuthenticator.proxy(_, clientNonceGenerator)) } .flatMap { case (secondResponse, proxyAuthHeader) => handleResponse( proxyAuthHeader.map(h => request.header(h)).getOrElse(request), secondResponse, DigestAuthTag, DigestAuthenticator.apply(_, clientNonceGenerator) ).map(_._1) } } private def handleResponse[T]( request: Request[T, S], response: Response[T], digestTag: String, digestAuthenticator: DigestAuthData => DigestAuthenticator ): F[(Response[T], Option[Header])] = { request .tag(digestTag) .map(_.asInstanceOf[DigestAuthData]) .flatMap { digestAuthData => val header = digestAuthenticator(digestAuthData).authenticate(request, response) header.map(h => delegate.send(request.header(h)).map(_ -> Option(h))) } .getOrElse((response -> Option.empty[Header]).unit) } override def openWebsocket[T, WS_RESULT]( request: Request[T, S], handler: WS_HANDLER[WS_RESULT] ): F[WebSocketResponse[WS_RESULT]] = delegate.openWebsocket(request, handler) override def close(): F[Unit] = delegate.close() override def responseMonad: MonadError[F] = delegate.responseMonad } object DigestAuthenticationBackend { private[client] val DigestAuthTag = "__sttp_DigestAuth" private[client] val ProxyDigestAuthTag = "__sttp_ProxyDigestAuth" }
Example 154
Source File: EitherBackend.scala From sttp with Apache License 2.0 | 5 votes |
package sttp.client import sttp.client.monad.{EitherMonad, MonadError} import sttp.client.ws.WebSocketResponse import scala.language.higherKinds import scala.util.control.NonFatal class EitherBackend[S, WS_HANDLER[_]](delegate: SttpBackend[Identity, S, WS_HANDLER]) extends SttpBackend[Either[Throwable, *], S, WS_HANDLER] { override def send[T](request: Request[T, S]): Either[Throwable, Response[T]] = doTry(delegate.send(request)) override def openWebsocket[T, WS_RESULT]( request: Request[T, S], handler: WS_HANDLER[WS_RESULT] ): Either[Throwable, WebSocketResponse[WS_RESULT]] = doTry(delegate.openWebsocket(request, handler)) override def close(): Either[Throwable, Unit] = doTry(delegate.close()) private def doTry[T](t: => T): Either[Throwable, T] = { try Right(t) catch { case NonFatal(e) => Left(e) } } override def responseMonad: MonadError[Either[Throwable, *]] = EitherMonad }
Example 155
Source File: ConvertToFuture.scala From sttp with Apache License 2.0 | 5 votes |
package sttp.client.testing import sttp.client.Identity import scala.concurrent.Future import scala.language.higherKinds import scala.util.Try trait ConvertToFuture[F[_]] { def toFuture[T](value: F[T]): Future[T] } object ConvertToFuture { lazy val id: ConvertToFuture[Identity] = new ConvertToFuture[Identity] { override def toFuture[T](value: Identity[T]): Future[T] = Future.successful(value) } lazy val future: ConvertToFuture[Future] = new ConvertToFuture[Future] { override def toFuture[T](value: Future[T]): Future[T] = value } lazy val scalaTry: ConvertToFuture[Try] = new ConvertToFuture[Try] { override def toFuture[T](value: Try[T]): Future[T] = Future.fromTry(value) } }
Example 156
Source File: ToFutureWrapper.scala From sttp with Apache License 2.0 | 5 votes |
package sttp.client.testing import scala.concurrent.Future import scala.language.higherKinds import org.scalatest.exceptions.TestFailedException trait ToFutureWrapper { implicit final class ConvertToFutureDecorator[F[_], T](wrapped: => F[T]) { def toFuture()(implicit ctf: ConvertToFuture[F]): Future[T] = { try { ctf.toFuture(wrapped) } catch { case e: TestFailedException if e.getCause != null => Future.failed(e.getCause) } } } }
Example 157
Source File: HttpTestExtensions.scala From sttp with Apache License 2.0 | 5 votes |
package sttp.client.testing import org.scalajs.dom.FileReader import org.scalajs.dom.raw.{Event, UIEvent} import sttp.client._ import sttp.client.dom.experimental.{FilePropertyBag, File => DomFile} import sttp.client.internal.SparkMD5 import scala.concurrent.{Future, Promise} import scala.language.higherKinds import scala.scalajs.js import scala.scalajs.js.JSConverters._ import scala.scalajs.js.JavaScriptException import scala.scalajs.js.typedarray.AB2TA import HttpTest.endpoint trait HttpTestExtensions[F[_]] extends AsyncExecutionContext { self: HttpTest[F] => private def withTemporaryFile[T](content: Option[Array[Byte]])(f: DomFile => Future[T]): Future[T] = { val data = content.getOrElse(Array.empty) val file = new DomFile( Array(data.toTypedArray.asInstanceOf[js.Any]).toJSArray, "temp.txt", FilePropertyBag( `type` = "text/plain" ) ) f(file) } private def withTemporaryNonExistentFile[T](f: DomFile => Future[T]): Future[T] = withTemporaryFile(None)(f) private def md5FileHash(file: DomFile): Future[String] = { val p = Promise[String]() val fileReader = new FileReader() fileReader.onload = (_: UIEvent) => { val arrayBuffer = fileReader.result.asInstanceOf[scala.scalajs.js.typedarray.ArrayBuffer] val hash = SparkMD5.ArrayBuffer.hash(arrayBuffer) p.success(hash) } fileReader.onerror = (_: Event) => p.failure(JavaScriptException("Error reading file")) fileReader.onabort = (_: Event) => p.failure(JavaScriptException("File read aborted")) fileReader.readAsArrayBuffer(file) p.future } "body" - { "post a file" in { withTemporaryFile(Some(testBodyBytes)) { f => postEcho.body(f).send().toFuture().map { response => response.body should be(Right(expectedPostEchoResponse)) } } } } "download file" - { "download a binary file using asFile" in { withTemporaryNonExistentFile { file => val req = basicRequest.get(uri"$endpoint/download/binary").response(asFile(file)) req.send().toFuture().flatMap { resp => md5FileHash(resp.body.right.get).map { _ shouldBe binaryFileMD5Hash } } } } "download a text file using asFile" in { withTemporaryNonExistentFile { file => val req = basicRequest.get(uri"$endpoint/download/text").response(asFile(file)) req.send().toFuture().flatMap { resp => md5FileHash(resp.body.right.get).map { _ shouldBe textFileMD5Hash } } } } } "multipart" - { def mp = basicRequest.post(uri"$endpoint/multipart") "send a multipart message with a file" in { withTemporaryFile(Some(testBodyBytes)) { f => val req = mp.multipartBody(multipartFile("p1", f), multipart("p2", "v2")) req.send().toFuture().map { resp => resp.body should be(Right(s"p1=$testBody (${f.name}), p2=v2$defaultFileName")) } } } } }
Example 158
Source File: AbstractFetchHttpTest.scala From sttp with Apache License 2.0 | 5 votes |
package sttp.client.testing import org.scalatest.compatible.Assertion import sttp.client.Response import scala.concurrent.Future import scala.language.higherKinds abstract class AbstractFetchHttpTest[F[_], -S] extends HttpTest[F] { override protected def expectRedirectResponse( response: F[Response[String]], code: Int ): Future[Assertion] = { response.toFuture().failed.map { t => t.getMessage should be("Unexpected redirect") } } // the fetch spec requires multiple values with the same name to be sorted and joined together... // https://fetch.spec.whatwg.org/#concept-header-value override protected def cacheControlHeaders = Set("max-age=1000, no-cache") // the only way to set the content type is to use a Blob which has a default filename of 'blob' override protected def multipartStringDefaultFileName: Option[String] = Some("blob") // everything is reported as "scala.scalajs.js.JavaScriptException: TypeError: Failed to fetch" override protected def supportsSttpExceptions = false }
Example 159
Source File: CompatibilityMappers.scala From neotypes with MIT License | 5 votes |
package neotypes package implicits.mappers import scala.collection.generic._ import scala.collection.{immutable => i, mutable => m} import scala.{collection => c} import scala.language.implicitConversions import scala.language.higherKinds import scala.reflect.ClassTag trait CompatibilityMappers { implicit final def neotypesGenericCompanionToCBF[A, CC[X] <: c.GenTraversable[X]](fact: GenericCompanion[CC]): CanBuildFrom[Any, A, CC[A]] = scala.collection.compat.genericCompanionToCBF(fact) implicit final def neotypesSortedSetCompanionToCBF[A: Ordering, CC[X] <: c.SortedSet[X] with c.SortedSetLike[X, CC[X]]](fact: SortedSetFactory[CC]): CanBuildFrom[Any, A, CC[A]] = scala.collection.compat.sortedSetCompanionToCBF(fact) implicit final def neotypesArrayCompanionToCBF[A: ClassTag](fact: Array.type): CanBuildFrom[Any, A, Array[A]] = scala.collection.compat.arrayCompanionToCBF(fact) implicit final def neotypesMapFactoryToCBF[K, V, CC[A, B] <: Map[A, B] with c.MapLike[A, B, CC[A, B]]](fact: MapFactory[CC]): CanBuildFrom[Any, (K, V), CC[K, V]] = scala.collection.compat.mapFactoryToCBF(fact) implicit final def neotypesSortedMapFactoryToCBF[K: Ordering, V, CC[A, B] <: c.SortedMap[A, B] with c.SortedMapLike[A, B, CC[A, B]]](fact: SortedMapFactory[CC]): CanBuildFrom[Any, (K, V), CC[K, V]] = scala.collection.compat.sortedMapFactoryToCBF(fact) implicit final def neotypesBitSetFactoryToCBF(fact: BitSetFactory[c.BitSet]): CanBuildFrom[Any, Int, c.BitSet] = scala.collection.compat.bitSetFactoryToCBF(fact) implicit final def neotypesImmutableBitSetFactoryToCBF(fact: BitSetFactory[i.BitSet]): CanBuildFrom[Any, Int, i.BitSet] = scala.collection.compat.immutableBitSetFactoryToCBF(fact) implicit final def neotypesMutableBitSetFactoryToCBF(fact: BitSetFactory[m.BitSet]): CanBuildFrom[Any, Int, m.BitSet] = scala.collection.compat.mutableBitSetFactoryToCBF(fact) }
Example 160
Source File: TransmittableIterableCollections.scala From scala-loci with Apache License 2.0 | 5 votes |
package loci package transmitter import scala.collection.TraversableLike import scala.collection.generic.CanBuildFrom import scala.language.higherKinds trait TransmittableGeneralIterableCollections extends TransmittableDummy { this: Transmittable.type => final implicit def traversable[B, I, R, V[T] >: Null <: TraversableLike[T, V[T]]] (implicit transmittable: Transmittable[B, I, R], cbfI: CanBuildFrom[V[B], I, V[I]], cbfR: CanBuildFrom[V[I], R, V[R]]) : DelegatingTransmittable[V[B], V[I], V[R]] { type Delegates = transmittable.Type } = DelegatingTransmittable( provide = (value, context) => if (value == null) null else value map { context delegate _ }, receive = (value, context) => if (value == null) null else value map { context delegate _ }) } trait TransmittableIterableCollections extends TransmittableGeneralCollections { this: Transmittable.type => final implicit def identicalTraversable [T: IdenticallyTransmittable, V[T] <: TraversableLike[T, V[T]]] : IdenticallyTransmittable[V[T]] = IdenticallyTransmittable() }
Example 161
Source File: TransmittableIterableCollections.scala From scala-loci with Apache License 2.0 | 5 votes |
package loci package transmitter import scala.collection.TraversableLike import scala.collection.generic.CanBuildFrom import scala.language.higherKinds trait TransmittableGeneralIterableCollections extends TransmittableDummy { this: Transmittable.type => final implicit def traversable[B, I, R, V[T] >: Null <: TraversableLike[T, V[T]]] (implicit transmittable: Transmittable[B, I, R], cbfI: CanBuildFrom[V[B], I, V[I]], cbfR: CanBuildFrom[V[I], R, V[R]]) : DelegatingTransmittable[V[B], V[I], V[R]] { type Delegates = transmittable.Type } = DelegatingTransmittable( provide = (value, context) => if (value == null) null else value map { context delegate _ }, receive = (value, context) => if (value == null) null else value map { context delegate _ }) } trait TransmittableIterableCollections extends TransmittableGeneralCollections { this: Transmittable.type => final implicit def identicalTraversable [T: IdenticallyTransmittable, V[T] <: TraversableLike[T, V[T]]] : IdenticallyTransmittable[V[T]] = IdenticallyTransmittable() }
Example 162
Source File: Continue.scala From Dsl.scala with Apache License 2.0 | 5 votes |
package com.thoughtworks.dsl.keywords import com.thoughtworks.dsl.Dsl import com.thoughtworks.dsl.Dsl.{!!, Keyword} import com.thoughtworks.enableMembersIf import scala.language.implicitConversions import scala.language.higherKinds import scala.util.control.TailCalls import scala.util.control.TailCalls.TailRec import scala.collection._ case object Continue extends Continue with Keyword[Continue, Nothing] { implicit def continueUnitDsl[Value]: Dsl[Continue, Unit, Value] = new Dsl[Continue, Unit, Value] { def cpsApply(keyword: Continue, handler: Value => Unit): Unit = () } @enableMembersIf(scala.util.Properties.versionNumberString.matches("""^2\.1(1|2)\..*$""")) private[dsl] object Scala211Or212 { type Factory[-A, +C] = scala.collection.generic.CanBuildFrom[Nothing, A, C] @inline def empty[A, C](implicit factory: Factory[A, C]): C = { factory().result() } } @enableMembersIf(scala.util.Properties.versionNumberString.matches("""^2\.13\..*$""")) private[dsl] object Scala213 { @inline def empty[A, C](implicit factory: Factory[A, C]): C = { factory.newBuilder.result() } } import Scala211Or212._ import Scala213._ implicit def collectionContinueDsl[Value, Element, Collection[_]]( implicit factory: Factory[Element, Collection[Element]]): Dsl[Continue, Collection[Element], Value] = new Dsl[Continue, Collection[Element], Value] { def cpsApply(keyword: Continue, handler: Value => Collection[Element]): Collection[Element] = { empty[Element, Collection[Element]] } } implicit def OptionContinueDsl[Value, Element]( implicit factory: Factory[Element, Option[Element]]): Dsl[Continue, Option[Element], Value] = new Dsl[Continue, Option[Element], Value] { def cpsApply(keyword: Continue, handler: Value => Option[Element]): Option[Element] = { None } } }
Example 163
Source File: PartialOrderDag.scala From crdt with Apache License 2.0 | 5 votes |
package com.machinomy.crdt.op import com.machinomy.crdt.op.PartialOrderDag.Update import com.machinomy.crdt.state.TPSet import scala.language.higherKinds import scalax.collection.Graph import scalax.collection.GraphPredef._ case class PartialOrderDag[V, E[X] <: DiEdgeLikeIn[X]](vertices: TPSet[V], edges: Set[E[V]])(implicit graphLike: DiGraphLike[V, E, Graph[V, E]]) { lazy val value: Graph[V, E] = graphLike.buildGraph(vertices.value, edges) def add(v: V, left: V, right: V): PartialOrderDag.UpdateResult[V, E] = { if (!value.contains(v) && graphLike.existsPath(value, left, right)) { val nextVertices = vertices + v val leftEdge = graphLike.buildEdge(left, v).edge val rightEdge = graphLike.buildEdge(v, right).edge val nextEdges = edges + leftEdge + rightEdge val next = new PartialOrderDag[V, E](nextVertices, nextEdges) (next, Some(PartialOrderDag.AddVertex[V, E](v, left, right))) } else { (this, None) } } // @todo This does not work. def remove(v: V): PartialOrderDag.UpdateResult[V, E] = if (value.contains(v) && !graphLike.isSentinel(v)) { val nextVertices = vertices - v val next = new PartialOrderDag[V, E](nextVertices, edges) (next, Some(PartialOrderDag.RemoveVertex[V, E](v))) } else { (this, None) } def run(operation: PartialOrderDag.AddVertex[V, E]): (PartialOrderDag[V, E], Option[Update[V, E]]) = add(operation.v, operation.left, operation.right) def run(operation: PartialOrderDag.RemoveVertex[V, E]): (PartialOrderDag[V, E], Option[Update[V, E]]) = remove(operation.v) } object PartialOrderDag { type UpdateResult[V, E[X] <: DiEdgeLikeIn[X]] = (PartialOrderDag[V, E], Option[Update[V, E]]) sealed trait Update[V, E[X] <: DiEdgeLikeIn[X]] case class AddVertex[V, E[X] <: DiEdgeLikeIn[X]](v: V, left: V, right: V) extends Update[V, E] case class RemoveVertex[V, E[X] <: DiEdgeLikeIn[X]](v: V) extends Update[V, E] }
Example 164
Source File: DiGraphLike.scala From crdt with Apache License 2.0 | 5 votes |
package com.machinomy.crdt.op import scala.language.higherKinds import scalax.collection.Graph import scalax.collection.GraphEdge._ import scalax.collection.GraphPredef._ trait DiGraphLike[V, E[X] <: DiEdgeLikeIn[X], G <: Graph[V, E]] { def contains(graph: G, vertex: V): Boolean def addEdge(graph: G, edge: E[V] with OuterEdge[V, E]): G def addVertex(graph: G, vertex: V): G def fromVertex(graph: G, edge: E[V] with OuterEdge[V, E]): V def toVertex(graph: G, edge: E[V] with OuterEdge[V, E]): V def path(graph: G, from: V, to: V): Option[G#Path] def existsPath(graph: G, from: V, to: V): Boolean def buildEdge(from: V, to: V): E[V] with OuterEdge[V, E] // @todo CanBuildEdge def buildGraph(vertices: Set[V], edges: Set[E[V]]): G // @todo CanBuildGraph def isSentinel(v: V): Boolean // @todo CanDetectSentinel } object DiGraphLike { implicit object IntDiGraphLike extends DiGraphLike[Int, DiEdge, Graph[Int, DiEdge]] { override def contains(graph: Graph[Int, DiEdge], vertex: Int): Boolean = graph.contains(vertex) override def addEdge(graph: Graph[Int, DiEdge], edge: DiEdge[Int] with OuterEdge[Int, DiEdge]): Graph[Int, DiEdge] = graph + edge override def addVertex(graph: Graph[Int, DiEdge], vertex: Int): Graph[Int, DiEdge] = graph + vertex override def fromVertex(graph: Graph[Int, DiEdge], edge: DiEdge[Int] with OuterEdge[Int, DiEdge]): Int = edge.from override def toVertex(graph: Graph[Int, DiEdge], edge: DiEdge[Int] with OuterEdge[Int, DiEdge]): Int = edge.to override def path(graph: Graph[Int, DiEdge], from: Int, to: Int): Option[graph.Path] = for { fromVertex <- graph.find(from) toVertex <- graph.find(to) path <- fromVertex.pathTo(toVertex) } yield path override def existsPath(graph: Graph[Int, DiEdge], from: Int, to: Int): Boolean = path(graph, from, to).isDefined override def buildEdge(from: Int, to: Int): DiEdge[Int] = from ~> to override def buildGraph(vertices: Set[Int], edges: Set[DiEdge[Int]]): Graph[Int, DiEdge] = Graph.from(vertices, edges) override def isSentinel(v: Int): Boolean = v == 1 || v == 100 } }
Example 165
Source File: GraphLikeA.scala From crdt with Apache License 2.0 | 5 votes |
package com.machinomy.crdt.op import scala.language.higherKinds object GraphLikeA { trait VertexLike[A] trait SentinelLike[A] extends VertexLike[A] trait EdgeLike[A, V <: VertexLike[A]] { def u: V def v: V } trait GraphLike[A, V <: VertexLike[A], E <: EdgeLike[A, V]] { def vertices: Set[V] def edges: Set[E] def existsPath(u: V, v: V): Boolean def add(e: E): GraphLike[A, V, E] def add(v: V): GraphLike[A, V, E] } trait CanBuildEdge[A, V <: VertexLike[A], E <: EdgeLike[A, V]] { def buildEdge(u: V, v: V): E } trait CanBuildGraph[A, V <: VertexLike[A], E <: EdgeLike[A, V]] { def buildGraph(vertices: Set[V], edges: Set[E]): GraphLike[A, V, E] } }