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

Scala Reader类代码示例

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

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



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

示例1: DbReader

//设置package包名称以及导入依赖的类
import cats.data.Reader
import cats.syntax.applicative._

object DbReader {

  case class Db(usernames: Map[Int, String],
                passwords: Map[String, String])

  type DbReader[A] = Reader[Db, A]

  def findUsername(userId: Int): DbReader[Option[String]] =
    Reader(db => db.usernames.get(userId))

  def checkPassword(username: String, password: String): DbReader[Boolean] =
    Reader(db => db.passwords.get(username).contains(password))

  def checkLogin(userId: Int, password: String): DbReader[Boolean] =
    for {
      username <- findUsername(userId)
      passwordOk <- username.map { u => checkPassword(u, password) }
        .getOrElse(false.pure[DbReader])

    } yield passwordOk

  def main(args: Array[String]) = {
    val db = Db(
      Map(
        1 -> "dade",
        2 -> "kate",
        3 -> "margo"
      ), Map(
        "dade" -> "zerocool",
        "kate" -> "acidburn",
        "margo" -> "secret"
      )
    )

    println(checkLogin(1, "zerocool").run(db))
    println(checkLogin(4, "davinci").run(db))

  }
} 
开发者ID:mikegehard,项目名称:advanced-scala-with-cats-exercises,代码行数:43,代码来源:DbReader.scala


示例2: createSchemaWork

//设置package包名称以及导入依赖的类
package io.scalac.wtf.domain

import cats.data.Reader
import slick.jdbc.JdbcBackend.Database
import slick.lifted.TableQuery
import slick.driver.H2Driver.api._
import io.scalac.wtf.domain.tables.Users

trait DatabaseDependancy {

  val db = Database.forConfig("h2mem1")

  //Used for showcase only, the table should already exist in a realistic scenario
  def createSchemaWork = Reader((config: Config) =>
    {
      implicit val ec = config.ec
      for {
        _ <- TableQuery[Users].schema.create
      } yield ()
    }
  )
} 
开发者ID:ScalaConsultants,项目名称:whisky-tango-foxtrot,代码行数:23,代码来源:DatabaseDependancy.scala


示例3: registerUserRoute

//设置package包名称以及导入依赖的类
package io.scalac.wtf.domain

import akka.http.scaladsl.server.Directives._
import cats.data.{Reader, Xor}
import spray.json.{JsObject, JsString}

import UserService.createUser
import spray.json.DefaultJsonProtocol._
import cats.implicits._
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport._

trait UserRoutes {
  implicit val userFormat = jsonFormat2(NewUser)

  def registerUserRoute = Reader((config: Config) => {
    implicit val ec = config.ec
    path("register") {
      post {
        entity(as[NewUser]) { userRequest =>
          val user = User(email = userRequest.email, password = userRequest.password)
          val result = config.db.run(createUser(user))

          complete {
            result.map {
              case Xor.Left(errors) => JsString(errors.unwrap.mkString(" "))
              case Xor.Right(_) => JsObject.empty
            }
          }
        }
      }
    }
  })
} 
开发者ID:ScalaConsultants,项目名称:whisky-tango-foxtrot,代码行数:34,代码来源:UserRoutes.scala


示例4: TopicConfigurator

//设置package包名称以及导入依赖的类
package com.sky.kafka.configurator

import cats.data.Reader
import com.typesafe.scalalogging.LazyLogging

import scala.util.control.NonFatal
import scala.util.{Failure, Success, Try}

case class TopicConfigurator(topicReader: TopicReader, topicWriter: TopicWriter) extends LazyLogging {

  def configure(topic: Topic): Try[Unit] = {
    for {
      currentTopic <- topicReader.fetch(topic.name)
      _ <- failIfDifferentReplicationFactor(currentTopic, topic)
      _ <- updatePartitionsIfDifferent(currentTopic, topic)
      _ <- updateConfigIfDifferent(currentTopic, topic)
    } yield ()
  }.recoverWith {
    case TopicNotFound(_) =>
      logger.info(s"Topic ${topic.name} not found: creating.")
      topicWriter.create(topic)
    case NonFatal(t) =>
      logger.error(s"Error occurred whilst configuring topic ${topic.name}: ${t.getMessage}")
      Failure(t)
  }

  private def failIfDifferentReplicationFactor(oldTopic: Topic, newTopic: Topic): Try[Unit] =
    if (oldTopic.replicationFactor != newTopic.replicationFactor)
      Failure(ReplicationChangeFound)
    else
      Success(())


  private def updatePartitionsIfDifferent(oldTopic: Topic, newTopic: Topic): Try[Unit] =
    if (oldTopic.partitions != newTopic.partitions) {
      logger.info(s"Topic ${newTopic.name} has different number of partitions: updating.")
      topicWriter.updatePartitions(newTopic.name, newTopic.partitions)
    } else {
      Success(())
    }

  private def updateConfigIfDifferent(oldTopic: Topic, newTopic: Topic): Try[Unit] =
    if (oldTopic.config != newTopic.config) {
      logger.info(s"Topic ${newTopic.name} has different configuration: updating.")
      topicWriter.updateConfig(newTopic.name, newTopic.config)
    } else {
      Success(())
    }
}

object TopicConfigurator {
  def reader: Reader[AppConfig, TopicConfigurator] = KafkaAdminClient.reader.map(c => TopicConfigurator(c, c))
} 
开发者ID:sky-uk,项目名称:kafka-configurator,代码行数:54,代码来源:TopicConfigurator.scala


示例5: OnOff

//设置package包名称以及导入依赖的类
package smartii.lightwave.model

import cats.Id
import cats.data.{Kleisli, Reader}
import com.lightwaverf.api.model.DeviceMessage
import smartii.lightwave.Lookup


sealed trait Device

object OnOff {

  def apply(deviceMessage: DeviceMessage): Reader[Lookup, Kleisli[Id, Lookup, OnOff]] = Reader { lookup: Lookup =>
    Room(deviceMessage).map { room =>
      OnOff(id = deviceMessage.dev, name = lookup.getDeviceName(deviceMessage.dev), room = room)
    }
  }
}

case class OnOff(id: Int, name: String, room: Room) extends Device

object Dimmer {

  def apply(deviceMessage: DeviceMessage): Reader[Lookup, Kleisli[Id, Lookup, Dimmer]] = Reader { lookup: Lookup =>
    Room(deviceMessage).map { room =>
      Dimmer(id = deviceMessage.dev, name = lookup.getDeviceName(deviceMessage.dev), room = room)
    }
  }

  def apply2(deviceMessage: DeviceMessage): Reader[Lookup, Kleisli[Id, Lookup, Dimmer]] = Reader { lookup: Lookup =>
    Room(deviceMessage).map { room =>
      Dimmer(id = deviceMessage.dev, name = lookup.getDeviceName(deviceMessage.dev), room = room)
    }
  }
}

case class Dimmer(id: Int, name: String, room: Room) extends Device 
开发者ID:jimnybob,项目名称:lightwave-akka,代码行数:38,代码来源:Device.scala


示例6: OwnerController

//设置package包名称以及导入依赖的类
package com.trainologic.samples.petclinic.web

import monix.eval.Task
import cats.~>
import argonaut._
import org.atnos.eff._
import syntax.eff._
import ReaderEffect._
import monix.TaskEffect._
import org.http4s._, org.http4s.dsl._
import argonaut._
import com.trainologic.samples.petclinic._
import service.ClinicService
import repository.OwnerRepository
import model.Owner
import cats.data.Xor
import cats.data.Reader
import model.ArgonautCodecs._
import com.trainologic.samples.petclinic.repository.PetRepository
import com.trainologic.samples.petclinic.model.PetType

class OwnerController[M[_]] {

  object LastNameQueryParamMatcher extends QueryParamDecoderMatcher[String]("lastName")
  type BaseOwnerStack = Fx.fx4[DataAccessException Xor ?, Validate[String, ?], Reader[ClinicService[M], ?], Reader[OwnerRepository[M], ?]]
  type BasePetStack = Fx.fx4[DataAccessException Xor ?, Validate[String, ?], Reader[ClinicService[M], ?], Reader[PetRepository[M], ?]]
  //type S1 = FxAppend[Fx1[M], BaseStack]
  type S2 = FxAppend[Fx1[Task], BaseOwnerStack]
  type S3 = FxAppend[Fx1[Task], BasePetStack]

  implicit def ownersEncoder: EntityEncoder[Seq[Owner]] = jsonEncoderOf[Seq[Owner]]
  implicit def petTypesEncoder: EntityEncoder[Seq[PetType]] = jsonEncoderOf[Seq[PetType]]

  def populatePetTypes(implicit ev: M ~> Task): PartialFunction[Request, Eff[S3, Response]] = {
    case request @ GET -> Root / "petTypes" => for {
      service <- ask[S3, ClinicService[M]].into
      petTypes <- service.findPetTypes.transform(ev).into[S3]
      r <- async[S3, Response](Ok(petTypes).unsafePerformSync)
    } yield r

  }

  def processFindForm(implicit ev: M ~> Task): PartialFunction[Request, Eff[S2, Response]] = {
    case request @ GET -> Root / "owners" :? LastNameQueryParamMatcher(lastName) => for {
      service <- ask[S2, ClinicService[M]].into
      owners <- service.findOwnerByLastName(lastName).transform(ev).into[S2]
      r <- async[S2, Response](Ok(owners).unsafePerformSync)
    } yield r

  }

} 
开发者ID:Trainologic,项目名称:petclinic_eff,代码行数:53,代码来源:OwnerController.scala


示例7: OwnerServicePure

//设置package包名称以及导入依赖的类
package com.trainologic.samples.petclinic.service
import com.trainologic.samples.petclinic._
import repository.MapBasedReadOnlyOwnerRepository
import cats.Id
import cats.data.Xor
import cats.data.Reader
import model.Owner
import org.atnos.eff.all._
import org.atnos.eff.syntax.all._
import repository.OwnerRepository
import org.atnos.eff._
import web.OwnerController
import cats.syntax.applicative._
import cats.syntax.apply._
import cats.Applicative
import cats.implicits._
object OwnerServicePure extends App {

  
  def test1 = {
    val owners: Map[Int, Owner] = Map(
      1 -> Owner(Some(1), "john", "Davis", "TA", "TA", "0000"),
      2 -> Owner(Some(2), "john2", "Davis", "TA", "TA", "0000"),
      3 -> Owner(Some(3), "john3", "Bavis", "TA", "TA", "0000"))

    

    val service1 = new ClinicServiceImpl[Id]
    val check1 = for {
      owners <- service1.findOwnerByLastName("Davis")
    } yield owners.size == 2


    val simpleRepo = MapBasedReadOnlyOwnerRepository(owners)
    
    val result = runReader(simpleRepo)(check1).runXor.runNel.runPure
    println(result)


  }
  test1
} 
开发者ID:Trainologic,项目名称:petclinic_eff,代码行数:43,代码来源:OwnerTestPure.scala


示例8: Verifiers

//设置package包名称以及导入依赖的类
package com.amdg.fhtml.functions

import cats.data.Reader
import com.amdg.fhtml.types.Snippet

object Verifiers {

  import SnippetInternalOps._

  type Condition = Reader[Snippet, ExtractionError Either Snippet]

  def verifyThat(snippet: Snippet, condition: Condition): ExtractionError Either Snippet = condition run snippet

  object Conditions {

    def startsWith(expression: String): Condition = Reader { snippet =>
      Either.cond(
        test = snippet.startsWith(expression),
        right = snippet,
        left = ExtractionError(s"'$expression' needs to be the first character")
      )
    }

    def endsWith(expression: String): Condition = Reader { snippet =>
      Either.cond(
        test = snippet.endsWith(expression),
        right = snippet,
        left = ExtractionError(s"'$expression' needs to be the last character")
      )
    }

    lazy val nonEmpty: Condition = Reader { snippet =>
      Either.cond(
        test = snippet.nonEmpty,
        right = snippet,
        left = ExtractionError("Empty content")
      )
    }

    def nonEmptyBetween(start: String, end: String): Condition = Reader { snippet =>
      for {
        content <- snippet.cutBetween(start, end)
        _ <- Either.cond(
          test = content.nonEmpty,
          right = snippet,
          left = ExtractionError(s"Empty content between '$start' and '$end'")
        )
      } yield snippet
    }

    def hasNo(expression: String,
              atOrBefore: Int): Condition = Reader { snippet =>
      snippet.indexOfFirst(expression) match {
        case Right(expressionIdx) if expressionIdx <= atOrBefore => Left(ExtractionError(s"Found '$expression' when not expected"))
        case _ => Right(snippet)
      }
    }
  }

} 
开发者ID:AMDG-Solutions,项目名称:fhtml,代码行数:61,代码来源:Verifiers.scala


示例9: Extractors

//设置package包名称以及导入依赖的类
package com.amdg.fhtml.functions

import cats.data.Reader
import cats.syntax.either._
import com.amdg.fhtml.tags.{TagSnippet, TagName}
import com.amdg.fhtml.types.Snippet

object Extractors {

  import SnippetInternalOps._
  import Verifiers._
  import Conditions._

  def extractFrom[I, O](snippet: I,
                        predicate: Reader[I, ExtractionError Either O]): ExtractionError Either O = predicate run snippet

  object Predicates {

    def next[T](implicit tokenFinder: Reader[Snippet, ExtractionError Either T]): Reader[Snippet, ExtractionError Either T] = Reader { snippet =>
      for {
        nonWhitespace <- snippet.trimLeadingWhitespaces
        tag <- tokenFinder.run(nonWhitespace)
      } yield tag
    }

    implicit val rawTagFinder: Reader[Snippet, ExtractionError Either TagSnippet] = Reader { snippet =>
      for {
        _ <- verifyThat(snippet, startsWith("<")) leftMap (error => ExtractionError(s"no tag found: $error"))
        tag <- snippet.cut(from = "<", to = ">") leftMap (_ => ExtractionError(s"no tag found: '${snippet.value}'; ${snippet.startIdx}; ${snippet.endIdx}"))
        tagContent <- tag.cutBetween("<", ">") flatMap (_.trimLeadingWhitespaces)
        _ <- verifyThat(tagContent, nonEmpty) leftMap (_ => ExtractionError("empty tag"))
      } yield TagSnippet(tag)
    }

    val tagName: Reader[TagSnippet, ExtractionError Either TagName] = Reader { tag =>

      val maybeTagName = for {
        tagEndIdx <- tag.value.indexOfFirst(">")
        tagNameEndIdx <- tag.value.indexOfFirst(" ", before = tagEndIdx, offset = 1)
          .orElse(tag.value.indexOfFirst("/", before = tagEndIdx, offset = 1))
          .orElse(tag.value.indexOfFirst(">", before = tagEndIdx + 1, offset = 1))
        _ <- verifyThat(tag.value, hasNo("=", atOrBefore = tagNameEndIdx))
        tagName <- Right(tag.value.moveWindow(tag.value.startIdx + 1, tagNameEndIdx))
        _ <- verifyThat(tagName, nonEmpty) leftMap (_ => ExtractionError("tag name cannot be empty"))
      } yield TagName(tagName.toString)

      maybeTagName leftMap (error => ExtractionError("No tag name found"))
    }
  }

} 
开发者ID:AMDG-Solutions,项目名称:fhtml,代码行数:52,代码来源:Extractors.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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