是否可以"扩展"F#编译器来进行自定义编译时字符串检查?我正在考虑类似于StringFormat使用sprintf时对字符串的检查等.当我说"扩展"时,我并不是指构建编译器的自定义版本,我的意思是使用现有的支持技术.
在我的头顶,你可能有一个RegexFormat类型.您提供正则表达式,编译器将使用正则表达式进行静态分析.例如
//Setup RegexFormat with IP address regex and type abbreviation IpRegexFormat?
//Compile error. ipAddress expects IpRegexFormat!
let ip = ipAddress "192.168.banana.1"
Run Code Online (Sandbox Code Playgroud)
如果没有,也许这是我的类型提供者:) - 如果整个事情是一个可怕的想法,请告诉我!
我们在Fsharpx中有一个Regex类型提供程序.
以下是一些示例:
type PhoneRegex = Regex< @"(?<AreaCode>^\d{3})-(?<PhoneNumber>\d{3}-\d{4}$)">
[<Test>]
let ``Can call typed IsMatch function``() =
PhoneRegex.IsMatch "425-123-2345"
|> should equal true
[<Test>]
let ``Can call typed CompleteMatch function``() =
PhoneRegex().Match("425-123-2345").CompleteMatch.Value
|> should equal "425-123-2345"
[<Test>]
let ``Can return AreaCode in simple phone number``() =
PhoneRegex().Match("425-123-2345").AreaCode.Value
|> should equal "425"
[<Test>]
let ``Can return PhoneNumber property in simple phone number``() =
PhoneRegex().Match("425-123-2345").PhoneNumber.Value
|> should equal "123-2345"
Run Code Online (Sandbox Code Playgroud)
它并不完全符合您的要求,但我想您可以轻松地使用此类型提供程序并使用静态文字规则对其进行自定义.