Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom F# compiler string checks

Tags:

f#

Is it possible to "extend" the F# compiler to do custom compile-time string checks? I'm thinking of something similar to the checks on StringFormat strings when using sprintf etc. When I say "extend", I don't mean build a custom version of the compiler, I mean use existing supported techniques.

Off the top of my head, you might have a RegexFormat type. You provide the regex and the compiler would do the static analysis using the regex. E.g.

//Setup RegexFormat with IP address regex and type abbreviation IpRegexFormat?
//Compile error.  ipAddress expects IpRegexFormat!
let ip = ipAddress "192.168.banana.1" 

If not, maybe this is a type provider for me :) - If the whole thing is a terrible idea, let me know!

like image 916
bentayloruk Avatar asked Feb 14 '26 22:02

bentayloruk


1 Answers

We have a Regex type provider in Fsharpx.

Here are some samples:

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"

It's not exactly what you are looking for, but I guess you could easily take this type provider and customize it with your static literal rules.

like image 166
forki23 Avatar answered Feb 16 '26 21:02

forki23



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!