関数には1つのパラメータがあり、型は文字列ですが長さは4です。コンパイル時にこのパラメータを検証できますか?コンパイル時にスカラで文字列形式を検証する方法
haskellとF#には型レベルがあり、コンパイル時にnonEmptyListのように検証できます。
スカラーで作る方法。私はshaplessこれを行うことができると思うが、私は
は、事前の提案関数には1つのパラメータがあり、型は文字列ですが長さは4です。コンパイル時にこのパラメータを検証できますか?コンパイル時にスカラで文字列形式を検証する方法
haskellとF#には型レベルがあり、コンパイル時にnonEmptyListのように検証できます。
スカラーで作る方法。私はshaplessこれを行うことができると思うが、私は
は、事前の提案はい、シェーピングはこれを行うことができます。おそらく次のようなものです:
def f(s: Sized[IndexedSeq[Char], Nat._4]): ...
あなたはこれに直接文字列を渡すことはできません。 f(Sized('a', 'b', 'c', 'd'))
あなたはバニラスカラ座とすることはできませんありがとうござい理解していません。あなたはこのために特別なタイプを作成して行くことができる
最善のアプローチ -
その後case class SpecialString(string: String) {
require(string.length == 4)
}
、あなたの関数ではなくString
のパラメータとしてSpecialString
を受信します。
マクロの使用は、コンパイル時の検証のオプションでもあります。 http://blog.xebia.com/compile-time-evaluation-scala-macros/
私は文字列の検証機能を定義するために彼の例を変更した:Arnout Engelenことで、この記事を参照してください
object CompileTimeStringCheck {
import scala.language.experimental.macros
// This function exposed to consumers has a normal Scala type:
def stringCheck(s: String): String =
// but it is implemented as a macro:
macro CompileTimeStringCheck.stringCheck_impl
import scala.reflect.macros.blackbox.Context
// The macro implementation will receive a 'Context' and
// the AST's of the parameters passed to it:
def stringCheck_impl(c: Context)(s: c.Expr[String]): c.Expr[String] = {
import c.universe._
// We can pattern-match on the AST:
s match {
case Expr(Literal(Constant(nValue: String))) =>
// We perform the calculation:
val result = normalStringCheck(nValue)
// And produce an AST for the result of the computation:
c.Expr(Literal(Constant(result)))
case other =>
// Yes, this will be printed at compile time:
println("Yow!")
???
}
}
// The actual implementation is regular old-fashioned scala code:
private def normalStringCheck(s: String): String =
if (s.length == 4) return s
else throw new Exception("Baaaaaah!")
}
ここでキャッチ、しかしです:これは、それを使用する前にコンパイルする必要があり、すなわち、それをユルツ瓶などに入れます。 、再び
import CompileTimeStringCheck._
object Test extends App {
println(stringCheck("yes!"))
}
の詳細および元の溶液(http://blog.xebia.com/compile-time-evaluation-scala-macros/)のためArnout Engelenの記事を参照してください。そして、あなたは後でコンパイル時にそれを使用することができます。
ありがとうございますが、これは非常に複雑な笑です。 –