当前位置: 首页>>代码示例>>Scala>>正文


Scala State类代码示例

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


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

示例1: StorageTests

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

import cats.data.State

class StorageTests extends SlateSuite {

  implicit val storage = PureStorage

  "pure interpreter" - {
    "get key" in {
      val getKey =
        storage("key")
      getKey.run(Map.empty).value._2 shouldBe None
      getKey.run(Map("key" -> "v")).value._2 shouldBe Some("v")
    }
    "update key" in {
      val updateKey =
        storage.update("key", "value")
      updateKey.run(Map.empty).value._1 shouldBe Map("key" -> "value")
      updateKey.run(Map("key" -> "v")).value._1 shouldBe Map("key" -> "value")
    }
    "remove key" in {
      val removeKey =
        storage.remove("key")
      removeKey.run(Map.empty).value._1 shouldBe Map.empty
      removeKey.run(Map("key" -> "v")).value._1 shouldBe Map.empty
    }
    "getOrSet" in {
      def getOrSet(key: String, data: String): StringMapState[String] =
        for {
          oldValue <- storage(key)
          newValue <- oldValue.fold(storage.update(key, data).map(_ => data))(State.pure)
        } yield newValue
      val getOrSetKey =
        getOrSet("key", "value")
      getOrSetKey.run(Map.empty).value._1 shouldBe Map("key" -> "value")
      getOrSetKey.run(Map("key" -> "v")).value._1 shouldBe Map("key" -> "v")
    }
  }

} 
开发者ID:edmundnoble,项目名称:slate,代码行数:43,代码来源:StorageTests.scala

示例2: AccountGroupId

//设置package包名称以及导入依赖的类
package com.gilesc.mynab.account

import cats.data.State
import com.gilesc.commons.{Prepending, Removing}
import com.gilesc.mynab.transaction._

case class AccountGroupId(value: Long) extends AnyVal

object AccountGroup extends AccountGroupModule with Prepending with Removing {
  type AccountState = Vector[Account]

  val create: (AccountGroupId, AccountName) => AccountGroup = (id, name) =>
    AccountGroup(id, name, Vector.empty[Account])

  val add: Account => State[AccountGroup, Unit] = a =>
    State[AccountGroup, Unit] { group =>
      (group.copy(accounts = prepend(a, group.accounts)), ())
    }

  val sum: AccountState => BigDecimal =
    _.foldRight(BigDecimal(0)) { (acc, sum) =>
      Transaction.sum(acc.transactions) + sum
    }
}

case class AccountGroup(id: AccountGroupId, name: AccountName, accounts: Vector[Account]) {
  def transactions: Vector[Transaction] = accounts.head.transactions
} 
开发者ID:CraigGiles,项目名称:mynab,代码行数:29,代码来源:AccountGroup.scala

示例3: AccountId

//设置package包名称以及导入依赖的类
package com.gilesc.mynab
package account

import cats.data.State
import com.gilesc.commons.{Prepending, Removing}
import com.gilesc.mynab.transaction.Transaction

case class AccountId(value: Long) extends AnyVal

trait Account {
  def id: AccountId
  def name: AccountName
  def accountType: AccountType
  def transactions: Vector[Transaction]

  def copy(id: AccountId = id,
    name: AccountName = name,
    transactions: Vector[Transaction] = transactions) =

    this match {
      case BankingAccount(_, _, _) => BankingAccount(id, name, transactions)
      case LoanAccount(_, _, _) => LoanAccount(id, name, transactions)
      case InvestmentAccount(_, _, _) => InvestmentAccount(id, name, transactions)
      case RetirementAccount(_, _, _) => RetirementAccount(id, name, transactions)
  }
}

object Account extends AccountModule with Prepending with Removing {
  def apply(id: AccountId, account: AccountType, name: AccountName,
    transactions: Vector[Transaction]): Account = account match {
      case Banking => BankingAccount(id, name, transactions)
      case Loan => LoanAccount(id, name, transactions)
      case Investment => InvestmentAccount(id, name, transactions)
      case Retirement => RetirementAccount(id, name, transactions)
  }

  val create: (AccountId, AccountType, AccountName) => Account = (i, t, n) =>
    Account(i, t, n, Vector.empty[Transaction])

  val add: Transaction => State[Account, Unit] = trans =>
    State[Account, Unit] { acc =>
      (acc.copy(acc.id, acc.name, prepend(trans, acc.transactions)), ())
    }
} 
开发者ID:CraigGiles,项目名称:mynab,代码行数:45,代码来源:Account.scala

示例4: Algorithm

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

import cats.data.State
import cats.syntax.applicative._
import shapeless.the
import org.apache.commons.math3.ml.clustering.DoublePoint
import penlight.model._
import penlight.model.PointT
import penlight.algorithm.Algorithm.AlgorithmState
import penlight.model.data.DataPoint


abstract class Algorithm[S <: Serializable : Advancing] {
  type Context <: AlgorithmContext

  type C[_] = Context

  def score[_: C]( shape: S, point: PointT ): AnomalyPDM

  def evalOne[_: C]( point: DataPoint ): AlgorithmState[S] = {
    State[S, AnomalyPDM] { shape => ( the[Advancing[S]].advance( shape, point ), score( shape, point ) ) }
  }

  def evalAll[_: C]( shape: S, points: Seq[DoublePoint] ): AlgorithmState[S] = {
    points.foldLeft( shape.pure[AlgorithmState[S]] ){ (s, pt) => s flatMap { _ => evalOne( pt.toDataPoint ) } }
  }
}

object Algorithm {
  type AlgorithmState[S <: Serializable] = State[S, AnomalyPDM]
} 
开发者ID:dmrolfs,项目名称:penlight,代码行数:32,代码来源:Algorithm.scala

示例5: dbActionMarshaller

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

import akka.http.scaladsl.model.HttpResponse
import akka.http.scaladsl.marshalling.Marshaller
import akka.http.scaladsl.marshalling.{ ToEntityMarshaller, ToResponseMarshaller }
import cats.data.{ EitherT, State }

trait Marshallers {

  def dbActionMarshaller[S, A](initial: S)(onResponse: S => Unit)(
      implicit ma: ToEntityMarshaller[A],
      me: ToEntityMarshaller[PetClinicError])
    : ToResponseMarshaller[EitherT[State[S, ?], PetClinicError, A]] =
    Marshaller(implicit ec =>
      s => {
        val (s2, r) = s.value.run(initial).value
        onResponse(s2)
        r match {
          case Right(a) =>
            ma.map(me => HttpResponse(entity = me))(a)
          case Left(e) =>
            me.map(
              me =>
                e.httpErrorCode
                  .map(
                    code => HttpResponse(status = code, entity = me)
                  )
                  .getOrElse(HttpResponse(entity = me)))(e)
        }
    })
}

object Marshallers extends Marshallers 
开发者ID:juanjovazquez,项目名称:scala-petclinic,代码行数:34,代码来源:Marshallers.scala

示例6: MonteCarloRenderer

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

import cats.data.State
import com.typesafe.scalalogging.Logger


class MonteCarloRenderer(
    val width : Integer,
    val height : Integer,
    val scene : Scene
) extends Renderer {

    final override def radiance(
        ray : Ray,
        depth : Integer,
        acc : RGB,
        att : RGB
    ) : RNG.Type[RGB] = {
        scene.intersect(ray) match {
            case None => {
                State.pure(acc)
            }
            case Some((prim, isect)) => {
                val n = prim.normal(isect)
                val nl =
                    if (n.dot(ray.dir) < 0)
                        n
                    else
                        -n

                val newDepth = depth + 1

                val colour = prim.material.colour * att
                val acc2 = acc + prim.material.emission * att

                if (newDepth > 5) {
                    // Modified Russian roulette.
                    val max = colour.max * MathUtil.sqr(1.0 - depth / Renderer.MaxDepth)
                    for {
                        rnd <- RNG.nextDouble
                        result <- if (rnd >= max) {
                            State.pure(acc2).asInstanceOf[RNG.Type[RGB]]
                        } else {
                            prim.material.radiance(this, ray, newDepth, isect, n, nl, acc2, colour / max)
                        }
                    } yield result
                } else {
                    prim.material.radiance(this, ray, newDepth, isect, n, nl, acc2, colour)
                }
            }
        }
    }
}

object MonteCarloRenderer {
    val logger = Logger[MonteCarloRenderer]
} 
开发者ID:jon-hanson,项目名称:ScalaPT,代码行数:58,代码来源:MonteCarloRenderer.scala

示例7: StateTut

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

import cats.data.State
import cats.syntax.applicative._

object StateTut extends App {

  type CalcState[A] = State[List[Int], A]

  def evalOne(sym: String): CalcState[Int] =
    sym match {
      case "+" => operator(_ + _)
      case "-" => operator(_ - _)
      case "*" => operator(_ * _)
      case "/" => operator(_ / _)
      case a   => operand(a.toInt)
    }

  def operand(num: Int): CalcState[Int] =
    State[List[Int], Int] { stack => (num :: stack, num)}

  def operator(func: (Int, Int) => Int): CalcState[Int] =
    State[List[Int], Int] {
      case a :: b :: tail =>
        val ans = func(a, b)
        (ans :: tail, ans)
      case _ => sys.error("Impossible!")
    }

  val program = for {
    _ <- evalOne("1")
    _ <- evalOne("3")
    ans <- evalOne("/")
  } yield ans

  println(program.runA(List()).value)

  def evalAll(input: List[String]): CalcState[Int] = {
    val i = 0.pure[CalcState]
    input.foldLeft(i) { (a, b) => {
      a flatMap (_ => evalOne(b) )
    }}
  }

  println(evalAll(List("1", "2", "+")).runA(Nil).value)
} 
开发者ID:hnfmr,项目名称:advanced-scala,代码行数:47,代码来源:StateTut.scala

示例8: catsfree

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

import cats.{Id, ~>}
import cats.free.Free
import scala.collection.mutable

//examples.catsfree.catsfree
object catsfree {

  sealed trait KVOps[T]
  case class Put[T](key: String, value: T) extends KVOps[Unit]
  case class Get[T](key: String) extends KVOps[Option[T]]
  case class Delete(key: String) extends KVOps[Unit]

  type KVDsl[A] = Free[KVOps, A]

  //smart constructors
  def put[T](key: String, value: T): KVDsl[Unit] =
    Free.liftF[KVOps, Unit](Put[T](key, value))

  def get[T](key: String): KVDsl[Option[T]] =
    Free.liftF[KVOps, Option[T]](Get[T](key))

  def delete(key: String): KVDsl[Unit] =
    Free.liftF(Delete(key))

  // Update composes get and set, and returns nothing.
  def update[T](key: String, f: T => T): KVDsl[Unit] =
    for {
      vMaybe <- get[T](key)
      _ <- vMaybe.map(v => put[T](key, f(v))).getOrElse(Free.pure(()))
    } yield ()

  def compareAndSet[T](key: String, f: T => T): KVDsl[Unit] =
    for {
      vMaybe <- get[T](key)
      _ <- vMaybe.map(v => put[T](key, f(v))).getOrElse(Free.pure(()))
    } yield ()

  
  def putP[A](key: String, value: A) =
    State[Store, A] { kvs: Store =>
      (kvs.updated(key, value), value)
    }

  def getP[A](key: String) =
    State[Store, A] { kvs: Store =>
      (kvs,
       kvs.get(key).map(_.asInstanceOf[A]).getOrElse(null.asInstanceOf[A]))
    }

  val prog = for {
    _ <- putP("a", 12)
    _ <- putP("b", 8)
    a <- getP[Int]("a")
    b <- getP[Int]("b")
  } yield { a + b }

  val res0 = prog.run(mutable.Map[String, Any]())
  //res0.value
} 
开发者ID:haghard,项目名称:shapeless-playbook,代码行数:62,代码来源:catsfree.scala


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