gpt4 book ai didi

scala - 无形中HList结构的证明

转载 作者:行者123 更新时间:2023-12-01 09:34:45 24 4
gpt4 key购买 nike

有时我需要编译时证明 H <: HList 的每个元素类型为 T .可以用这段代码表示:

import shapeless._

@annotation.implicitNotFound("Cannot prove that A =:= ${T} forAll A in ${H}")
trait ForAll[H <: HList, T]

object ForAll {

implicit def head[T]: ForAll[T :: HNil, T] = new ForAll[T :: HNil, T] {}

implicit def tail[T, HT <: HList](implicit ttail: ForAll[HT, T]): ForAll[T :: HT, T] = new ForAll[T :: HT, T] {}
}
// an example
def chain[H <: HList, A](hlist: H)(a: A)(implicit allAreFunctions: ForAll[H, (A => A)]): A = {
def iter(h: HList, ax: A): A = h match {
case HNil => ax
case (f: (A => A)) :: tail => iter(tail, f(ax))
}

iter(hlist, a)
}

val hlist1 = ((_: Int) + 1) :: ((_: Int) * 1) :: ((_: Int) - 2) :: HNil
val hlist2 = ((_: Int).toString) :: ((_: Int) + 1) :: ((_: Int) - 2) ::HNil
chain(hlist1)(1)
// chain(hlist2)(1) doesn't compile

我可以忽略关于可能的匹配错误的编译器警告,因为 ForAll实例证明代码正确。

shapeless 是否实现了类似的东西(或者可能有更好的选择)?

最佳答案

ForAll 只是 shapeless.ops.hlist.LeftReducer 用于正确定义的 Poly。例如

import shapeless.{::, HNil, Poly2}
import shapeless.ops.hlist.LeftReducer

object myPoly extends Poly2 {
implicit def `case`[A]: Case.Aux[A, A, A] = at((x, y) => x)
}

implicitly[LeftReducer.Aux[Int :: Int :: Int :: Int :: HNil, myPoly.type, Int]]//compiles
implicitly[LeftReducer[Int :: Int :: Int :: Int :: HNil, myPoly.type]]//compiles
// implicitly[LeftReducer.Aux[Int :: Int :: String :: Int :: HNil, myPoly.type, Int]]//doesn't compile
// implicitly[LeftReducer[Int :: Int :: String :: Int :: HNil, myPoly.type]]//doesn't compile

LeftReducer[Int :: Int :: Int :: Int :: HNil, myPoly.type].apply(1 :: 2 :: 3 :: 4 :: HNil)//1
// LeftReducer[Int :: Int :: String :: Int :: HNil, myPoly.type].apply(1 :: 2 :: "a" :: 4 :: HNil)//doesn't compile

(1 :: 2 :: 3 :: 4 :: HNil).reduceLeft(myPoly)//1
// (1 :: 2 :: "a" :: 4 :: HNil).reduceLeft(myPoly)//doesn't compile

关于scala - 无形中HList结构的证明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50470363/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com