我正在使用Shapeless 2.0,并尝试使用HList验证输入,尽可能多地在编译时进行检查。
我有一个HList“spec”,指定了我期望的输入类型(类型应在编译时进行检查),并且还可以包括要执行的运行时检查(例如,测试数字是偶数还是奇数)。
考虑以下规格:
我应该如何编写一个函数,以便有效地执行以下操作:
以下内容将发生:
我有一个HList“spec”,指定了我期望的输入类型(类型应在编译时进行检查),并且还可以包括要执行的运行时检查(例如,测试数字是偶数还是奇数)。
考虑以下规格:
trait Pred[T] { def apply(t: T): Boolean }
val IsString = new Pred[String] { def apply(s: String) = true }
val IsOddNumber = new Pred[Int] { def apply(n: Int) = n % 2 != 0 }
val IsEvenNumber = new Pred[Int] { def apply(n: Int) = n % 2 == 0 }
val spec = IsEvenNumber :: IsString :: IsString :: IsOddNumber :: HNil
还有各种示例输入:
val goodInput = 4 :: "foo" :: "" :: 5 :: HNil
val badInput = 4 :: "foo" :: "" :: 4 :: HNil
val malformedInput = 4 :: 5 :: "" :: 6 :: HNil
我应该如何编写一个函数,以便有效地执行以下操作:
input.zip(spec).forall{case (input, test) => test(input)}
以下内容将发生:
因此,以下情况会发生:
f(spec, goodInput) // true
f(spec, badInput) // false
f(spec, malformedInput) // Does not compile
(goodInput zipWith spec)(check)
- 但要注意它不需要长度匹配。 - Travis BrownLength
;添加了关于为什么不使用Mapped
的说明)。 - Seth Tisue