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

Scala State类代码示例

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

本文整理汇总了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;未经允许,请勿转载。


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Scala InternetAddress类代码示例发布时间:2022-05-23
下一篇:
Scala ILoggingEvent类代码示例发布时间: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