在 shapeless 中,有两个列表,其中一个包含另一个的类型类 [英] In shapeless, have two lists such that one contains typeclasses of the other

查看:36
本文介绍了在 shapeless 中,有两个列表,其中一个包含另一个的类型类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 shapeless 中,我正在尝试编写一个函数,该函数采用两个任意长度的 HList l1l2,它们具有以下属性:

In shapeless I'm trying to write a function such that takes two HLists l1 and l2 of arbitrary length which exhibit the following properties:

  1. l1l2 的长度相同.
  2. l2 包含 l1 的确切类型,包裹在一个常量外部类型构造函数中.
  1. Length of l1 and l2 are the same.
  2. l2 contains the exact types of l1, wrapped in a constant outer type constructor.

所以,如果 l1

1 :: 1.2 :: "hello" :: HNil`

l2 可以是

Ordering[Int] :: Ordering[Double] :: Ordering[String] :: HNil

使用 UnaryTCConstraintLengthAux 让我限制长度并需要 l2 的静态外部构造函数,但是让它们符合已经成为一个问题.

Using UnaryTCConstraint and LengthAux lets me constrain the lengths and require a static outer constructor for l2, however having them conform has become a problem.

关于我如何去做的任何想法?

Any ideas on how I could go about it?

推荐答案

Mapped 精确地提供了这种约束,而无需额外的 Length.来自 文档:

Mapped provides precisely this constraint without the additional need for Length. From the documentation:

类型类见证包装每个元素的结果HList L 在类型构造器 F 中是 Out.

Type class witnessing that the result of wrapping each element of HList L in type constructor F is Out.

这是它在 1.2.4 中的样子:

Here's how it looks in 1.2.4:

import shapeless._

def foo[L1 <: HList, L2 <: HList](l1: L1, l2: L2)(implicit
  ev: MappedAux[L1, Ordering, L2]
) = ()

val l1 = 1 :: 1.2 :: "hello" :: HNil
val l2 = Ordering[Int] :: Ordering[Double] :: Ordering[String] :: HNil
val l3 = Ordering[Int] :: Ordering[Double] :: Ordering[Char] :: HNil

然后:

scala> foo(l1, l2)

scala> foo(l1, l3)
<console>:17: error: could not find implicit value for parameter ev: ...

正如预期的那样.对于 2.0,只需添加一个 shapeless.ops.hlist._ 导入并将 MappedAux 替换为 Mapped.Aux,您就可以开始使用了.

As expected. For 2.0 just add a shapeless.ops.hlist._ import and replace MappedAux with Mapped.Aux and you're ready to go.

这篇关于在 shapeless 中,有两个列表,其中一个包含另一个的类型类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆