以下要点有我正在玩的想法的代码
package com.test1
import scala.language.implicitConversions
import shapeless._
import FromTraversable._
import Traversables._
import Nat._
import Tuples._
trait ToArity[P, N <: Nat]
object ToArity {
implicit def prod1[P <: Product1[_]] = new ToArity[P, _1] {}
implicit def prod2[P <: Product2[_, _]] = new ToArity[P, _2] {}
// ad nauseum...
}
trait SizedHListAux[A, N <: Nat, T <: HList]
object SizedHListAux {
implicit def base[A, H <: HList] = new SizedHListAux[A, _0, HNil] {}
implicit def induct[A, H <: HList, N <: Nat, …Run Code Online (Sandbox Code Playgroud) 给定是一个Java方法,它返回java.lang.Object给定字符串的s.我想将此方法包装在Scala方法中,该方法将返回的实例转换为某种类型T.如果转换失败,则应返回该方法None.我正在寻找类似的东西:
def convert[T](key: String): Option[T] = {
val obj = someJavaMethod(key)
// return Some(obj) if obj is of type T, otherwise None
}
convert[Int]("keyToSomeInt") // yields Some(1)
convert[String]("keyToSomeInt") // yields None
Run Code Online (Sandbox Code Playgroud)
(如何)使用Scala的反射API可以实现这一目标吗?我很清楚,convert可能必须改变签名.
在我正在研究的Play应用程序中,我正在尝试改进我们的系统以处理标志,其中一些是用户通过链接导航我们的应用程序时的持久选项.我想使用Shapeless从选项的定义映射到它的值,并且还仅从标记为要传播的参数合成新的查询参数.我还希望能够利用Shapeless的Record功能来获得参数值的强类型解除引用.不幸的是,我不确定我是否在Shapeless中以有效的方式接近它.
以下是一段代码,被一些解释性注释所打断.
以下是我正在使用的基本数据类型:
import shapeless._
import poly._
import syntax.singleton._
import record._
type QueryParams = Map[String, Seq[String]]
trait RequestParam[T] {
def value: T
/** Convert value back to a query parameter representation */
def toQueryParams: Seq[(String, String)]
/** Mark this parameter for auto-propagation in new URLs */
def propagate: Boolean
protected def queryStringPresent(qs: String, allParams: QueryParams): Boolean = allParams.get(qs).nonEmpty
}
type RequestParamBuilder[T] = QueryParams => RequestParam[T]
def booleanRequestParam(paramName: String, willPropagate: Boolean): RequestParamBuilder[Boolean] = { params =>
new RequestParam[Boolean] { …Run Code Online (Sandbox Code Playgroud) 我目前正在尝试在scala中定义时钟数据流语言的模型.
流程实际上代表某种类型T的无限序列值,由某个时钟C调节(时钟表示流量实际可用的时刻).
通过根据从另一个(布尔)流F'导出的时钟C本身对其进行采样,可以从流F导出采样流SF:SF包含当布尔流F'为真时采样的F的值.
"基本时钟"是从名为"T"的始终为真的流派生的时钟.
在下面的示例中,F和F'位于基准时钟上(并且 - 用于表示流在某个时刻没有值)
T : 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 ... (always 1)
F : 0 0 0 1 1 1 0 1 0 1 0 0 0 1 1 1 1 ...
F' : 0 1 0 0 0 1 0 1 1 1 0 0 0 1 0 0 1 ...
F sampled on F': - 0 - - - 1 - …Run Code Online (Sandbox Code Playgroud) scala path-dependent-type dependent-type type-level-computation shapeless
我目前正在实现一个库来序列化和反序列化XML-RPC消息.它几乎已经完成,但现在我正在尝试使用Shapeless删除当前asProduct方法的样板.我目前的代码:
trait Serializer[T] {
def serialize(value: T): NodeSeq
}
trait Deserializer[T] {
type Deserialized[T] = Validation[AnyErrors, T]
type AnyErrors = NonEmptyList[AnyError]
def deserialize(from: NodeSeq): Deserialized[T]
}
trait Datatype[T] extends Serializer[T] with Deserializer[T]
// Example of asProduct, there are 20 more methods like this, from arity 1 to 22
def asProduct2[S, T1: Datatype, T2: Datatype](apply: (T1, T2) => S)(unapply: S => Product2[T1, T2]) = new Datatype[S] {
override def serialize(value: S): NodeSeq = {
val params = …Run Code Online (Sandbox Code Playgroud) 在下面,我试图创建一个多态函数将a转换RawFeatureValue为a RefinedFeatureValue.
import shapeless._
object test {
type RawFeatureValue = Int :+: Double :+: String :+: CNil
type RefinedFeatureValue = Int :+: Double :+: CNil
private object convert extends Poly1 {
implicit def caseInt = at[Int](i => i)
implicit def caseDouble = at[Double](d => d)
implicit def caseString = at[String](s => s.hashCode)
}
val a = Coproduct[RawFeatureValue](12)
val b: RefinedFeatureValue = a map convert
}
Run Code Online (Sandbox Code Playgroud)
但是,结果类型Int :+: Double :+: Int :+: CNil与之不兼容RefinedFeatureValue.
[error] …Run Code Online (Sandbox Code Playgroud) 我是新手,并且一直在尝试练习某种类型级别的编程.我将Project Euler的问题#1作为我的第一个挑战.
我开始编写常规的scala代码:
object ProjectEuler1 {
def e1(limit: Int) = (1 until limit).foldLeft(0) {
case (acc, x) if x % 3 * x % 5 == 0 => acc + x
case (acc, _) => acc
}
val out = e1(10)
assert(out == 23)
}
Run Code Online (Sandbox Code Playgroud)
然后,我想出了这个工作无形的实现poly:
object ProjectEuler1Shapeless extends App {
import shapeless._
import nat._
import ops.nat._
import poly._
import test.typed
trait eLP extends Poly1 {
implicit def default[A <: Nat] = at[A] { _ => …Run Code Online (Sandbox Code Playgroud) Slick的支持HList通常是一件好事.不幸的是,它带有自己的实现,几乎不提供任何有用的操作.因此,我想用无形 HList代替.这应该是" 微不足道的 ",但我不知道如何做到这一点.在网上搜索我发现没有证据表明某人设法完成了这项任务.
我认为这足以实现ProvenShape(如广告在这里),但因为我不明白的概念,油滑的 (Proven)Shape S,我没实现这一点.
我基本上是想把它煮沸
class Users( tag: Tag )
extends Table[Long :: String :: HNil]( tag, "users" )
{
def id = column[Long]( "id", O.PrimaryKey, O.AutoInc )
def email = column[String]( "email" )
override def * = ( id, email ) <>[TableElementType, ( Long, String )](
_.productElements,
hlist => Some( hlist.tupled )
)
}
Run Code Online (Sandbox Code Playgroud)
向下
class Users( tag: Tag )
extends Table[Long :: String :: HNil]( …Run Code Online (Sandbox Code Playgroud) 我想以某种方式在编译时获取val中的case类的字段的名称(可能是单例类型的字符串或符号?).
类似于以下内容:
import shapeless._
case class MyClass(field1: String, field2: Int)
val field1Lens = lens[MyClass] >> 'field1
// val name = field1Lens.name // it should be "field1", aka 'field1.name
Run Code Online (Sandbox Code Playgroud)
我没有必要使用镜头,任何有效的技术都很好(有什么LabelledGeneric?).我想有一些东西,我可以获得案例类字段的名称,而无需单独指定它.这样,如果我重构field1类中成员的名称,则name相应地进行更改.
当然以下不起作用,因为宏在编译时不知道符号的名称:
val name = 'field1
val field1Lens = lens[MyClass] >> name // can't possibly work
Run Code Online (Sandbox Code Playgroud)
我试过lens[MyClass] >> name.narrow但它也不起作用
这就是我目前正在做的事情,当然我不喜欢它:
// If I change the name of the field, compilation fails
// and I'm forced to check this line of code so I can …Run Code Online (Sandbox Code Playgroud) 我需要从一个case类实例创建一个更新的实例(带有任何需要DecodeJson的隐式派生),给定一个不完整的json(缺少一些字段).如何通过Argonaut(最好)或Circe(如果必须的话)实现这一目标?
例:
case class Person(name:String, age:Int)
val person = Person("mr complete", 42)
val incompletePersonJson = """{"name":"mr updated"}"""
val updatedPerson = updateCaseClassFromIncompleteJson(person, incompletePersonJson)
println(updatedPerson)
//yields Person(mr updated, 42)
Run Code Online (Sandbox Code Playgroud)
我很确定我必须将json解析为json AST,然后将其转换为Shapeless LabelledGeneric,然后以某种方式使用Shapeless更新来更新case类实例.
编辑2
在阅读了Shapeless源代码后,我发现我可以生成自己的"默认"对象.我设法创建了一个解决方案,它需要在解析json时出现case类的实例.我希望避免这种情况,而是稍后提供实例.无论如何它是:
import shapeless._
import argonaut._
import ArgonautShapeless._
import shapeless.ops.hlist.Mapper
case class Person(name: String, age: Int)
object MkDefault {
object toSome extends Poly1 {
implicit def default[P] = at[P](Some(_))
}
def apply[P, L <: HList, D <: HList]
(p: P)
(implicit
g: Generic.Aux[P, L],
mpr: Mapper.Aux[toSome.type, L, …Run Code Online (Sandbox Code Playgroud)