什么是无形中的 Case.Aux [英] what is Case.Aux in shapeless

查看:32
本文介绍了什么是无形中的 Case.Aux的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对无形特征概述中显示的示例感到困惑.

I am confused about the example shown in the shapeless feature overview.

object size extends Poly1 {
  implicit def caseInt = at[Int](x => 1)
  implicit def caseString = at[String](_.length)
  implicit def caseTuple[T, U]
    (implicit st : Case.Aux[T, Int], su : Case.Aux[U, Int]) =
      at[(T, U)](t => size(t._1)+size(t._2))
}

scala> size(((23, "foo"), 13))
res7: Int = 5

  1. Case.Aux 是什么?
  2. 为什么参数化类型是 Int 而不是 String
  3. 如果 size(((23, "foo", 123), 13)), 如何定义 CaseTuple ?

非常感谢

推荐答案

有关 PolyN 函数的更多说明,您可以在这里找到:什么是at"在无形(scala)中?

More explanations about PolyN function you can find here: What is "at" in shapeless (scala)?

1 &2.所以让我们重写这段代码,使其更清晰:

1 & 2. So let's rewrite this code to make it more clear:

object size extends Poly1 {
  implicit def caseInt = at[Int](x => 1)
  implicit def caseString = at[String](_.length)
  implicit def caseTuple[T, U]
    (implicit st : Case.Aux[T, Int], su : Case.Aux[U, Int]) =
      at[(T, U)](t => st(t._1) + su(t._2))
}

Case 类型类为我们提供了将一些 poly 函数应用于具有它的类型的某个对象.http://xuwei-k.github.io/shapeless-sxr/shapeless-2.10-2.0.0-M1/shapeless/poly.scala.html#shapeless.PolyDefns;Case

Case type class provides us applying some poly function to some object with it's type. http://xuwei-k.github.io/shapeless-sxr/shapeless-2.10-2.0.0-M1/shapeless/poly.scala.html#shapeless.PolyDefns;Case

让我们尝试创建一些函数:

Let's try to make some function:

def sizeF[F, S](t: (F, S)) = size(t)

这是不可能的,没有定义如何应用函数的类型类:

It is impossible, without type class wich defines how to apply function:

def sizeF[F, S](t: (F, S))
(implicit cse: Case[size.type, (F, S) :: HNil]) = size(t)

Case.Aux[T, U] 它是一个快捷方式: poly.Case[this.type, T :: HNil]{ type Result = U }T - 它是一个参数,U - 应用后的结果类型.

Case.Aux[T, U] it is a shortcut for: poly.Case[this.type, T :: HNil]{ type Result = U } T - it is an argument, U - the result type after application.

3. 让我们修改函数并使 ((23, "foo", 123), 13) 可用,我们需要添加函数来处理三元组:

3. Let's modify function and make avalible application to ((23, "foo", 123), 13), we need to add function to work with triples:

object size extends Poly1 {
  implicit def caseInt = at[Int](x => 1)
  implicit def caseString = at[String](_.length)
  implicit def caseTuple[T, U]
  (implicit st : Case.Aux[T, Int], su : Case.Aux[U, Int]) =
    at[(T, U)](t => size(t._1) + size(t._2))
  implicit def caseTriple[T, U, F]
  (implicit st : Case.Aux[T, Int], su : Case.Aux[U, Int], sf: Case.Aux[F, Int]) =
    at[(T, U, F)](t => size(t._1) + size(t._2) + size(t._3))
}

size(((23, "foo", 123), 13)) //> res0: Int = 6

正如预期的那样.

这篇关于什么是无形中的 Case.Aux的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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