• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Scala Free类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Scala中cats.free.Free的典型用法代码示例。如果您正苦于以下问题:Scala Free类的具体用法?Scala Free怎么用?Scala Free使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了Free类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Scala代码示例。

示例1: compileF_

//设置package包名称以及导入依赖的类
package tierney.free

import cats.~>
import cats.free.Free
import tierney.core.FunctorK
import cats.Monad

trait FreeSupport {
  def compileF_[F[_], G[_]](f: F ~> G): Free[F, ?] ~> Free[G, ?] = Lambda[Free[F, ?] ~> Free[G, ?]](_.compile(f))
  implicit val compileF__ : FunctorK[Free] = new FunctorK[Free] {
    override def map[F[_], G[_]](f: F ~> G) = compileF_(f)
  }
  def foldMapF_[F[_], G[_]: Monad](f: F ~> G): Free[F, ?] ~> G = Lambda[Free[F, ?] ~> G](_.foldMap(f))
  def liftF_[F[_]]: F ~> Free[F, ?] = Lambda[F ~> Free[F, ?]](Free.liftF(_))
  def runTailRec_[F[_]: Monad]: Free[F, ?] ~> F = Lambda[Free[F, ?] ~> F](_.runTailRec)
}
object FreeSupport extends FreeSupport 
开发者ID:m50d,项目名称:tierney,代码行数:18,代码来源:FreeSupport.scala


示例2: IndexLogic

//设置package包名称以及导入依赖的类
package com.yannick_cw.elastic_indexer4s.indexing_logic

import akka.NotUsed
import akka.stream.scaladsl.Source
import cats.data.EitherT
import cats.free.Free
import cats.free.Free.liftF
import com.yannick_cw.elastic_indexer4s.Index_results.{IndexError, RunResult, StageSucceeded}

object IndexLogic {
  sealed trait IndexAction[A]
  type FreeIndexAction[A] = Free[IndexAction, A]
  type StageResult = Either[IndexError, StageSucceeded]
  type StageAction[A] = EitherT[FreeIndexAction, IndexError, A]

  case object CreateIndex extends IndexAction[StageResult]
  case class IndexSource[A](source: Source[A, NotUsed]) extends IndexAction[StageResult]
  case class SwitchAlias(minT: Double, maxT: Double, alias: String) extends IndexAction[StageResult]
  case class DeleteOldIndices(keep: Int, aliasProtection: Boolean) extends IndexAction[StageResult]

  // lifts the Algebra into a free context and than into EitherT for easier operations
  private def createIndex: StageAction[StageSucceeded] = EitherT(liftF(CreateIndex): FreeIndexAction[StageResult])
  private def indexSource[A](source: Source[A, NotUsed]): StageAction[StageSucceeded] =
    EitherT(liftF[IndexAction, StageResult](IndexSource(source)): FreeIndexAction[StageResult])
  private def switchAlias(minT: Double, maxT: Double, alias: String): StageAction[StageSucceeded] =
    EitherT(liftF(SwitchAlias(minT, maxT, alias)): FreeIndexAction[StageResult])
  private def deleteOldIndices(keep: Int, aliasProtection: Boolean): StageAction[StageSucceeded] =
    EitherT(liftF(DeleteOldIndices(keep, aliasProtection)): FreeIndexAction[StageResult])

  private def addRunStep(actionDone: StageAction[RunResult], nextStep: StageAction[StageSucceeded]) = for {
    indexResult <- actionDone
    success <- nextStep
      .leftMap(_.copy(succeededStages = indexResult.succeededStages.toList))
  } yield RunResult(indexResult.succeededStages :+ success: _*)

  def write[A](source: Source[A, NotUsed]): StageAction[RunResult] =
    addRunStep(createIndex.map(RunResult(_)), indexSource(source))

  def addSwitch(writeDone: StageAction[RunResult], minT: Double, maxT: Double, alias: String) =
    addRunStep(writeDone, switchAlias(minT, maxT, alias))

  def addDelete(writeDone: StageAction[RunResult], keep: Int, aliasProtection: Boolean) =
    addRunStep(writeDone, deleteOldIndices(keep, aliasProtection))
} 
开发者ID:yannick-cw,项目名称:elastic-indexer4s,代码行数:45,代码来源:IndexLogic.scala


示例3: apply

//设置package包名称以及导入依赖的类
package llsm.interpreters

import cats.{ApplicativeError, ~>}
import cats.free.Free
import io.scif.img.ImgOpener
import llsm.algebras.{ImgReaderAPI, ImgReaderF, LoggingAPI, LoggingF}
import llsm.fp._
import llsm.io.LLSMImg
import net.imglib2.img.ImgFactory
import net.imglib2.`type`.numeric.integer.UnsignedShortType
import org.scijava.Context

trait ImgReaderInterpreters {

  
  val readerLogging: ImgReaderF ~< Halt[LoggingF, ?] =
    new (ImgReaderF ~< Halt[LoggingF, ?]) {
      def apply[A](fa: ImgReaderF[A]): Free[Halt[LoggingF, ?], A] =
        fa match {
          case ImgReaderAPI.ReadImg(path, meta, _) =>
            Free.liftF[Halt[LoggingF, ?], A](
              LoggingAPI[LoggingF].debug(s"Reading image: $path")
            )
        }
    }
} 
开发者ID:keithschulze,项目名称:llsm,代码行数:27,代码来源:reader.scala


示例4: deskewImg

//设置package包名称以及导入依赖的类
package llsm.algebras

import cats.free.{Free, Inject}
import llsm.InterpolationMethod
import llsm.io.LLSMImg


trait ProcessAPI[F[_]] {
  def deskewImg(img: LLSMImg, shearDim: Int, refDim: Int, shearFactor: Double, interpolation: InterpolationMethod): F[LLSMImg]
}

sealed trait ProcessF[A]

object ProcessAPI {

  case class DeskewImg[A](img: LLSMImg,
                          shearDim: Int,
                          refDim: Int,
                          shearFactor: Double,
                          interpolation: InterpolationMethod,
                          next: LLSMImg => A) extends ProcessF[A]

  implicit val process = new ProcessAPI[ProcessF] {
    def deskewImg(img: LLSMImg, shearDim: Int, refDim: Int, shearFactor: Double, interpolation: InterpolationMethod): ProcessF[LLSMImg] =
      DeskewImg(img, shearDim, refDim, shearFactor, interpolation, identity)
  }

  implicit def processInject[F[_], G[_]](implicit F: ProcessAPI[F], I: Inject[F, G]): ProcessAPI[Free[G, ?]] =
    new ProcessAPI[Free[G, ?]] {
      def deskewImg(img: LLSMImg, shearDim: Int, refDim: Int, shearFactor: Double, interpolation: InterpolationMethod): Free[G, LLSMImg] =
        Free.inject[F, G](F.deskewImg(img, shearDim, refDim, shearFactor, interpolation))
    }
} 
开发者ID:keithschulze,项目名称:llsm,代码行数:34,代码来源:process.scala


示例5: get

//设置package包名称以及导入依赖的类
package llsm.algebras

import cats.free.{Free, Inject}

trait ConfigAPI[F[_]] {
  def get[A](key: String): F[Option[A]]
  def put[A](key: String, value: A): F[Unit]
  def delete(key: String): F[Unit]
  def update[A](key: String, f: A => A): F[Unit]
}

sealed trait ConfigF[A]
case class Get[A, T](key: String, next: Option[T] => A) extends ConfigF[A]
case class Put[A, T](key: String, value: T, next: Unit => A) extends ConfigF[A]
case class Delete[A](key: String, next: Unit => A) extends ConfigF[A]

object ConfigAPI {
  def apply[F[_]](implicit ev: ConfigAPI[Free[F, ?]]): ConfigAPI[Free[F, ?]] = ev

  implicit val config = new ConfigAPI[ConfigF] {
    def get[A](key: String): ConfigF[Option[A]] = Get[Option[A], A](key, identity)
    def put[A](key: String, value: A): ConfigF[Unit] = Put(key, value, identity)
    def delete(key: String): ConfigF[Unit] = Delete(key, identity)
    def update[A](key: String, f: A => A): ConfigF[Unit] =
      Get(key, (a: Option[A]) => a match {
        case Some(a) => { put[A](key, f(a)); ()}
        case None => ()
      })
  }

  implicit def configInject[F[_], G[_]](implicit F: ConfigAPI[F], I: Inject[F, G]): ConfigAPI[Free[G, ?]] =
    new ConfigAPI[Free[G, ?]] {
      def get[A](key: String): Free[G, Option[A]] = Free.inject[F, G](F.get[A](key))
      def put[A](key: String, value: A): Free[G, Unit] = Free.inject[F, G](F.put[A](key, value))
      def delete(key: String): Free[G, Unit] = Free.inject[F, G](F.delete(key))
      def update[A](key: String, f: A => A): Free[G, Unit] = Free.inject[F, G](F.update(key, f))
    }
} 
开发者ID:keithschulze,项目名称:llsm,代码行数:39,代码来源:config.scala


示例6: progress

//设置package包名称以及导入依赖的类
package llsm.algebras

import cats.free.{Free, Inject}

trait ProgressAPI[F[_]] {
  def progress(value: Int, max: Int): F[Unit]
  def status(message: String): F[Unit]
}

sealed trait ProgressF[A]

object ProgressAPI {

  case class Progress(value: Int, max: Int) extends ProgressF[Unit]
  case class Status(message: String) extends ProgressF[Unit]

  implicit val progress = new ProgressAPI[ProgressF] {
    def progress(value: Int, max: Int): ProgressF[Unit] =
      Progress(value, max)
    def status(message: String): ProgressF[Unit] =
      Status(message)
  }

  implicit def progressInject[F[_], G[_]](
    implicit
    F: ProgressAPI[F],
    I: Inject[F, G]
  ): ProgressAPI[Free[G, ?]] =
    new ProgressAPI[Free[G, ?]] {
      def progress(value: Int, max: Int): Free[G, Unit] =
        Free.inject[F, G](F.progress(value, max))
      def status(message: String): Free[G, Unit] =
        Free.inject[F, G](F.status(message))
    }
} 
开发者ID:keithschulze,项目名称:llsm,代码行数:36,代码来源:progress.scala


示例7: info

//设置package包名称以及导入依赖的类
package llsm.algebras

import cats.free.{Free, Inject}

trait LoggingAPI[F[_]] {
  def info(msg: String): F[Unit]
  def infoCause(msg: String, cause: Throwable): F[Unit]
  def warn(msg: String): F[Unit]
  def warnCause(msg: String, cause: Throwable): F[Unit]
  def debug(msg: String): F[Unit]
  def debugCause(msg: String, cause: Throwable): F[Unit]
  def error(msg: String): F[Unit]
  def errorCause(msg: String, cause: Throwable): F[Unit]
  def trace(msg: String): F[Unit]
  def traceCause(msg: String, cause: Throwable): F[Unit]
}

sealed trait LoggingF[A]

object LoggingAPI {
  def apply[F[_]](implicit ev: LoggingAPI[F]): LoggingAPI[F] = ev

  case class Info(msg: String) extends LoggingF[Unit]
  case class InfoCause(msg: String, cause: Throwable) extends LoggingF[Unit]
  case class Warn(msg: String) extends LoggingF[Unit]
  case class WarnCause(msg: String, cause: Throwable) extends LoggingF[Unit]
  case class Debug(msg: String) extends LoggingF[Unit]
  case class DebugCause(msg: String, cause: Throwable) extends LoggingF[Unit]
  case class Error(msg: String) extends LoggingF[Unit]
  case class ErrorCause(msg: String, cause: Throwable) extends LoggingF[Unit]
  case class Trace(msg: String) extends LoggingF[Unit]
  case class TraceCause(msg: String, cause: Throwable) extends LoggingF[Unit]


  implicit val logging = new LoggingAPI[LoggingF] {
    def info(msg: String): LoggingF[Unit] = LoggingAPI.Info(msg)
    def infoCause(msg: String, cause: Throwable): LoggingF[Unit] = LoggingAPI.InfoCause(msg, cause)
    def warn(msg: String): LoggingF[Unit] = LoggingAPI.Warn(msg)
    def warnCause(msg: String, cause: Throwable): LoggingF[Unit] = LoggingAPI.WarnCause(msg, cause)
    def debug(msg: String): LoggingF[Unit] = LoggingAPI.Debug(msg)
    def debugCause(msg: String, cause: Throwable): LoggingF[Unit] = LoggingAPI.DebugCause(msg, cause)
    def error(msg: String): LoggingF[Unit] = LoggingAPI.Error(msg)
    def errorCause(msg: String, cause: Throwable): LoggingF[Unit] = LoggingAPI.ErrorCause(msg, cause)
    def trace(msg: String): LoggingF[Unit] = LoggingAPI.Trace(msg)
    def traceCause(msg: String, cause: Throwable): LoggingF[Unit] = LoggingAPI.TraceCause(msg, cause)
  }

  implicit def loggingInject[F[_], G[_]](implicit F: LoggingAPI[F], I: Inject[F, G]): LoggingAPI[Free[G, ?]] =
    new LoggingAPI[Free[G, ?]] {
      def info(msg: String): Free[G, Unit] = Free.inject[F, G](F.info(msg))
      def infoCause(msg: String, cause: Throwable): Free[G, Unit] = Free.inject[F, G](F.infoCause(msg, cause))
      def warn(msg: String): Free[G, Unit] = Free.inject[F, G](F.warn(msg))
      def warnCause(msg: String, cause: Throwable): Free[G, Unit] = Free.inject[F, G](F.warnCause(msg, cause))
      def debug(msg: String): Free[G, Unit] = Free.inject[F, G](F.debug(msg))
      def debugCause(msg: String, cause: Throwable): Free[G, Unit] = Free.inject[F, G](F.debugCause(msg, cause))
      def error(msg: String): Free[G, Unit] = Free.inject[F, G](F.error(msg))
      def errorCause(msg: String, cause: Throwable): Free[G, Unit] = Free.inject[F, G](F.errorCause(msg, cause))
      def trace(msg: String): Free[G, Unit] = Free.inject[F, G](F.trace(msg))
      def traceCause(msg: String, cause: Throwable): Free[G, Unit] = Free.inject[F, G](F.traceCause(msg, cause))
    }
} 
开发者ID:keithschulze,项目名称:llsm,代码行数:62,代码来源:logging.scala


示例8: writeImg

//设置package包名称以及导入依赖的类
package llsm.algebras

import java.nio.file.Path
import cats.free.{Free, Inject}

import llsm.io.LLSMImg
import llsm.io.metadata.FileMetadata

trait ImgWriterAPI[F[_]] {
  def writeImg(path: Path, img: LLSMImg): F[FileMetadata]
}

sealed trait ImgWriterF[A]

object ImgWriterAPI {
  def apply[F[_]](implicit ev: ImgWriterAPI[F]): ImgWriterAPI[F] = ev

  case class WriteImg[A](path: Path, img: LLSMImg, next: FileMetadata => A) extends ImgWriterF[A]

  implicit val imgWriter = new ImgWriterAPI[ImgWriterF] {
    def writeImg(path: Path, img: LLSMImg): ImgWriterF[FileMetadata] = WriteImg(path, img, identity)
  }

  implicit def imgWriterInject[F[_], G[_]](implicit F: ImgWriterAPI[F], I: Inject[F, G]): ImgWriterAPI[Free[G, ?]] =
    new ImgWriterAPI[Free[G, ?]] {
      def writeImg(path: Path, img: LLSMImg): Free[G, FileMetadata] =
        Free.inject[F, G](F.writeImg(path, img))
    }
}

sealed trait LowWriterF[A]
case class WriteOMETIFF(path: Path, img: LLSMImg) extends LowWriterF[FileMetadata]
case class WriteHDF5(path: Path, img: LLSMImg) extends LowWriterF[FileMetadata]

object LowWriterAPI {
  def writeOMETIFF(path: Path, img: LLSMImg): Free[LowWriterF, FileMetadata] =
    Free.liftF[LowWriterF, FileMetadata](WriteOMETIFF(path, img))
  def writeHDF5(path: Path, img: LLSMImg): Free[LowWriterF, FileMetadata] =
    Free.liftF[LowWriterF, FileMetadata](WriteHDF5(path, img))
} 
开发者ID:keithschulze,项目名称:llsm,代码行数:41,代码来源:writer.scala


示例9: Orders

//设置package包名称以及导入依赖的类
package objektwerks.cats

object Orders {
  type Symbol = String
  type Amount = Double
  type Response = String
  sealed trait Orders[A]
  case class Buy(stock: Symbol, amount: Amount) extends Orders[Response]
  case class Sell(stock: Symbol, amount: Amount) extends Orders[Response]
}

object OrdersDsl {
  import Orders._
  import cats.free.Free

  type OrdersFree[A] = Free[Orders, A]

  def buy(stock: Symbol, amount: Amount): OrdersFree[Response] = Free.liftF[Orders, Response](Buy(stock, amount))
  def sell(stock: Symbol, amount: Amount): OrdersFree[Response] = Free.liftF[Orders, Response](Sell(stock, amount))
}

object OrdersInterpreter {
  import Orders._
  import cats.{Id, ~>}

  def interpreter: Orders ~> Id = new (Orders ~> Id) {
    def apply[A](order: Orders[A]): Id[A] = order match {
      case Buy(stock, amount) =>
        println(s"Buying $amount of $stock")
        "ok"
      case Sell(stock, amount) =>
        println(s"Selling $amount of $stock")
        "ok"
    }
  }
}

object OrdersProgram {
  import OrdersDsl._
  import OrdersInterpreter._
  import cats.Id

  val program = for {
    _ <- buy("APPL", 100.0)
    _ <- buy("MSFT", 10.0)
    response <- sell("GOOG", 110.0)
  } yield response

  def run(): Id[Unit] = program foldMap interpreter
}


object OrdersFreeMonadApp extends App {
  OrdersProgram.run()
} 
开发者ID:objektwerks,项目名称:typelevel,代码行数:56,代码来源:OrdersFreeMonadApp.scala


示例10: free

//设置package包名称以及导入依赖的类
import cats._
import cats.free.{Free, Inject}
import sio.core._
import sio.teletype
import sio.core.instances.all._
import sio.core.syntax.st._

object free {
  sealed abstract class Interact[A] extends Product with Serializable
  object Interact {
    final case class Ask(message: String) extends Interact[String]
    final case class Tell(message: String) extends Interact[Unit]
  }

  class Interacts[F[_]](implicit F: Inject[Interact, F]) {
    def ask(message: String): Free[F, String] = Free.inject(Interact.Ask(message))
    def tell(message: String): Free[F, Unit] = Free.inject(Interact.Tell(message))
  }
  object Interacts {
    implicit def interacts[F[_]](implicit I: Inject[Interact, F]): Interacts[F] = new Interacts[F]
  }

  type App[A] = Interact[A]

  def program(implicit I: Interacts[App]): Free[App, Unit] = {
    import I._

    for {
      name <- ask("Hello, what's your name?")
      _    <- tell(s"Hey, $name")
    } yield ()
  }

  object InteractIOInterpreter extends (Interact ~> ST[RW, ?]) {
    def apply[A](i: Interact[A]) = i match {
      case Interact.Ask(x) => teletype.putStrLn(x) >> teletype.getLine
      case Interact.Tell(x) => teletype.putStrLn(x)
    }
  }

  def main: IO[Unit] = program.foldMap(InteractIOInterpreter)
} 
开发者ID:alexknvl,项目名称:sio,代码行数:43,代码来源:free.scala


示例11: Service

//设置package包名称以及导入依赖的类
package org.channing.free

import cats.free.Free
import cats.free.Free._
import cats.~>

object Service {
  type ServiceOp[A] = Free[ServiceOpA, A]

  sealed trait ServiceOpA[A]

  object GreatComplexService extends ServiceOpA[String]

  def greatComplexService: ServiceOp[String] =
    liftF[ServiceOpA, String](GreatComplexService)

  import Layer1._
  def layerInterpreter: ServiceOpA ~> L1Op =
    new (ServiceOpA ~> L1Op) {
      def apply[A](fa: ServiceOpA[A]): L1Op[A] =
        fa match {
          case GreatComplexService =>
            for {
              a ? Layer1.op1("hi")
              b ? Layer1.op1("bye")
            } yield a + b
        }
    }
} 
开发者ID:channingwalton,项目名称:doobie-play,代码行数:30,代码来源:Service.scala


示例12: Layer1

//设置package包名称以及导入依赖的类
package org.channing.free

import cats.free.Free
import cats.free.Free._
import cats.~>

object Layer1 {
  type L1Op[A] = Free[L1OpA, A]

  sealed trait L1OpA[A]

  case class Op1(arg: String) extends L1OpA[String]

  def op1(arg: String): L1Op[String] =
    liftF[L1OpA, String](Op1(arg))


  import Store._
  def storeInterpreter: L1OpA ~> KVStore =
    new (L1OpA ~> KVStore) {
      def apply[A](fa: L1OpA[A]): KVStore[A] =
        fa match {
          case Op1(arg) =>
            get(arg).map(_.getOrElse("whatever"))
        }
    }
} 
开发者ID:channingwalton,项目名称:doobie-play,代码行数:28,代码来源:Layer1.scala


示例13: node

//设置package包名称以及导入依赖的类
package tierney.free

import cats.free.Free
import cats.Applicative
import tierney.core._
import CoproductSupport._
import FreeApplicativeSupport._
import FreeSupport._
import cats.data.Coproduct
import cats.~>
import cats.arrow.FunctionK
import cats.Monad
import tierney.parallel.ParallelApplicative
import cats.free.FreeApplicative


trait TierneyFree[F[_], A] extends Any {
  def node: Node[F, A] = Node.right(serial)
  def parallel: Parallel[F, A] = FreeApplicative.lift[Node[F, ?], A](node)
  def serial: Serial[F, A] = Free.liftF[Parallel[F, ?], A](parallel)

  final def compile[G[_]](f: F ~> G): Node[G, A] = functorKNode.map(f).apply(node)

  private[this] def run(implicit mo: Monad[F], ap: Applicative[F]): F[A] =
    node.cata[IdKK](
      foldCP_[F, Free[FreeApplicative[F, ?], ?], F](
        FunctionK.id,
        foldMapF_[FreeApplicative[F, ?], F](fold_(ap)))
    )(NodeSerialParallelF.functorKKNodeSerialParallelF)

  final def runSerialOrUnprincipled(implicit mo: Monad[F]): F[A] = run
  final def runSerialOrUnprincipled[G[_]](f: F ~> G)(implicit mo: Monad[G]): G[A] = compile(f).runSerialOrUnprincipled

  final def runParallel(implicit mo: Monad[F], pa: ParallelApplicative[F]): F[A] = run(mo, pa)
  final def runParallel[G[_]](f: F ~> G)(implicit mo: Monad[G], pa: ParallelApplicative[G]): G[A] = compile(f).runParallel
} 
开发者ID:m50d,项目名称:tierney,代码行数:37,代码来源:TierneyFree.scala


示例14: childrenOf

//设置package包名称以及导入依赖的类
package mco.io.files

import java.nio.file.attribute.BasicFileAttributes

import cats.free.Free
import freasymonad.cats.free

// $COVERAGE-OFF$Macro-generated code
@free sealed trait MonadicIO {
  sealed trait OperationsADT[A]
  type FreeIO[A] = Free[OperationsADT, A]

  def childrenOf(path: Path)                     : FreeIO[Stream[Path]]
  def descendantsOf(path: Path)                  : FreeIO[Stream[Path]]
  def removeFile(path: Path)                     : FreeIO[Unit]
  def isRegularFile(path: Path)                  : FreeIO[Boolean]
  def isDirectory(path: Path)                    : FreeIO[Boolean]
  def archiveEntries(path: Path)                 : FreeIO[Set[String]]
  def extract(path: Path, ft: Map[String, Path]) : FreeIO[Unit]
  def readBytes(path: Path)                      : FreeIO[Array[Byte]]
  def setContent(path: Path, cnt: Array[Byte])   : FreeIO[Unit]
  def createDirectory(path: Path)                : FreeIO[Unit]
  def copyTree(source: Path, dest: Path)         : FreeIO[Unit]
  def moveTree(source: Path, dest: Path)         : FreeIO[Unit]
  def stat(path: Path)                           : FreeIO[BasicFileAttributes]
}
// $COVERAGE-ON 
开发者ID:oleg-py,项目名称:mco,代码行数:28,代码来源:MonadicIO.scala


示例15: LogAlgebra

//设置package包名称以及导入依赖的类
package log4free

import cats.free.Free

object LogAlgebra {
  import Logging._
  
  object log {
    
    def debug(msg: String): Free[LogF, Unit] =
      Free.liftF(Debug(msg, ()))
    
    def info(msg: String): Free[LogF, Unit]  =
      Free.liftF(Info(msg, ()))
    
    def warn(msg: String): Free[LogF, Unit]  =
      Free.liftF(Warn(msg, ()))
    
    def error(msg: String): Free[LogF, Unit] =
      Free.liftF(Error(msg, ()))
  }
  
  sealed trait LogF[+A]
  object Logging {
    case class Debug[A](msg: String, o: A) extends LogF[A]
    case class Info[A](msg: String, o: A) extends LogF[A]
    case class Warn[A](msg: String, o: A) extends LogF[A]
    case class Error[A](msg: String, o: A) extends LogF[A]
  }

} 
开发者ID:sun-opsys,项目名称:free-monad-workshop,代码行数:32,代码来源:LogAlgebra.scala


示例16: Main

//设置package包名称以及导入依赖的类
package log4free

import cats.free.Free

object Main {
  import LogAlgebra._
  import LogAlgebra.log
  
  val program: Free[LogF, Unit] =
    for {
      a <- log.info("fooo")
      b <- log.error("OH NOES")
    } yield b
  
  def main(args: Array[String]): Unit = {
    Println(program)
  }
} 
开发者ID:sun-opsys,项目名称:free-monad-workshop,代码行数:19,代码来源:Main.scala


示例17: LogBinder

//设置package包名称以及导入依赖的类
package log4free

import cats.free.Free
import cats.Functor
import LogAlgebra._
import LogAlgebra.Logging._

object LogBinder {
  
  type Log[A] = Free[LogF, A]
  
  implicit def logFFunctor[B]: Functor[LogF] = new Functor[LogF]{

    def map[A,B](fa: LogF[A])(f: A => B): LogF[B] =
      fa match {
        case Debug(msg,a) => Debug(msg,f(a))
        case Info(msg,a)  => Info(msg,f(a))
        case Warn(msg,a)  => Warn(msg,f(a))
        case Error(msg,a) => Error(msg,f(a))
      }
  }
  
} 
开发者ID:sun-opsys,项目名称:free-monad-workshop,代码行数:24,代码来源:LogBinder.scala


示例18: ReadLine

//设置package包名称以及导入依赖的类
package me.panavtec.tictactoe

import cats.free.{Free, Inject}
import cats.{Id, ~>}
import me.panavtec.tictactoe.Domain._

import scala.io.StdIn

sealed trait Console[A]
case object ReadLine extends Console[Coordinate]
case class PrintLine(line: String) extends Console[Unit]

object Console {
  val interpreter: Console ~> Id = new (Console ~> Id) {
    override def apply[A](fa: Console[A]): Id[A] = {
      fa match {
        case ReadLine => Coordinate.fromString(StdIn.readLine).get
        case PrintLine(line) => println(line)
      }
    }
  }
}

class ConsoleOps[F[_]](implicit I: Inject[Console, F]) {
  def readLine: Free[F, Coordinate] = Free.inject(ReadLine)

  def printLine(line: String): Free[F, Unit] = Free.inject(PrintLine(line))
}

object ConsoleOps {
  implicit def console[F[_]](implicit I: Inject[Console, F]): ConsoleOps[F] = new ConsoleOps[F]
} 
开发者ID:PaNaVTEC,项目名称:TicTacToe,代码行数:33,代码来源:Console.scala


示例19: Start

//设置package包名称以及导入依赖的类
package me.panavtec.tictactoe

import cats.free.{Free, Inject}
import cats.{Id, ~>}
import me.panavtec.tictactoe.Domain.{Board, Mark, O_, X_}
import me.panavtec.tictactoe.GameEngine.{GameState, PlayerInput}

sealed trait Game[A]
case object Start extends Game[GameState]
case class PlayAt(board: Board, playerInput: PlayerInput) extends Game[GameState]

object Game {
  val interpreter: Game ~> Id = new (Game ~> Id) {
    override def apply[A](fa: Game[A]): Id[A] = {
      fa match {
        case Start => (X_, Board.emptyBoard)
        case PlayAt(board, (coordinate, X_)) => (O_, Board.playAt(board, coordinate, X_))
        case PlayAt(board, (coordinate, O_)) => (X_, Board.playAt(board, coordinate, O_))
      }
    }
  }

  def hasFinished(gs: GameState): Boolean = gs match {
    case (_ , b) => Board.hasPlayerWon(b) || Board.isBoardFull(b)
  }
}

class GameOps[F[_]](implicit I: Inject[Game, F]) {
  def startGame: Free[F, GameState] = Free.inject(Start)

  def playNext(board: Board, playerInput: PlayerInput): Free[F, GameState] = Free.inject(PlayAt(board, playerInput))
}

object GameOps {
  implicit def turn[F[_]](implicit I: Inject[Game, F]): GameOps[F] = new GameOps[F]
} 
开发者ID:PaNaVTEC,项目名称:TicTacToe,代码行数:37,代码来源:Game.scala


示例20: GameEngine

//设置package包名称以及导入依赖的类
package me.panavtec.tictactoe

import cats.data.Coproduct
import cats.free.Free
import cats.{Id, ~>}
import me.panavtec.tictactoe.Domain.{Board, Coordinate, Mark}

object GameEngine {

  type PlayerInput = (Coordinate, Mark)
  type GameState = (Mark, Board)
  type TicTacToeApp[A] = Coproduct[Console, Game, A]
  val interpreter: TicTacToeApp ~> Id = Console.interpreter or Game.interpreter

  val I: ConsoleOps[TicTacToeApp] = implicitly[ConsoleOps[TicTacToeApp]]
  val D: GameOps[TicTacToeApp] = implicitly[GameOps[TicTacToeApp]]

  import D._
  import I._

  def init: GameState = startTicTacToe.flatMap(initialGameState =>
    iterateUntil(Game.hasFinished)(initialGameState, turn)
  ).foldMap(interpreter)

  def startTicTacToe: Free[TicTacToeApp, GameState] = {
    for {
      _ <- printLine("== Game Starts ==")
      gameState <- startGame
    } yield gameState
  }

  def turn(gameState: GameState): Free[TicTacToeApp, GameState] = {
    val (player: Mark, board: Board) = gameState
    for {
      _ <- printLine(s"Turn Of Player ${Mark.stringRepresentation(player)}. Input next move [X,Y]:")
      coordinate <- readLine
      newGameState <- playNext(board, (coordinate, player))
      _ <- printLine(Board.stringRepresentation(newGameState._2))
    } yield newGameState
  }

  def iterateUntil[A[_], S](pred: S => Boolean)(initialState: S, next: S => Free[A, S]): Free[A, S] = {
    next(initialState).flatMap(nextState =>
      if (pred(nextState)) Free.pure(nextState)
      else iterateUntil(pred)(nextState, next)
    )
  }
} 
开发者ID:PaNaVTEC,项目名称:TicTacToe,代码行数:49,代码来源:GameEngine.scala



注:本文中的cats.free.Free类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Scala FormError类代码示例发布时间:2022-05-23
下一篇:
Scala TreeMap类代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap