patternMinor
Defining a zip code string
Viewed 0 times
codezipstringdefining
Problem
I'm following this
and am trying to make more of these with hopefully less repetition. Can this be done without having to repeat type
See all the repetition? For the purpose of defining a zip code, a US zip code could be defined as
or
let StringOfLengthConstructor (input:string, length:int, defaultConstructor:string->'c) =
match input with
| null -> None
| x when x.Length = length -> Some(defaultConstructor(input))
| _ -> None
type String3 = | String3 of string
let String3 input = StringOfLengthConstructor(input, 3, String3)
type String4 = | String4 of string
let String4 input= StringOfLengthConstructor(input, 4, String4)
type String5 = | String5 of string
let String5 input = StringOfLengthConstructor(input, 5, String5)
type String6 = | String6 of string
let String6 input = StringOfLengthConstructor(input,6, String6)and am trying to make more of these with hopefully less repetition. Can this be done without having to repeat type
String3 =| String3 of string followed by this?let String3 input = StringOfLengthConstructor(input, 3, String3)See all the repetition? For the purpose of defining a zip code, a US zip code could be defined as
type ZipCode = | Us of String5or
type ZipCode = | Us of String5*(String4 option) | Canadian of String3*String3Solution
The solution can be made cleaner by re-arranging the order of the arguments and using pointfree style.
However, I don't think that
let StringOfLengthConstructor (length : int) (defaultConstructor : string -> 'c) (input : string) =
match input with
| x when x <> null && x.Length = length -> Some (defaultConstructor input)
| _ -> None
type String3 = String3 of string
let String3 = StringOfLengthConstructor 3 String3However, I don't think that
String5 * (String4 option) is a good definition of a zip code. The code should be validating on more than just the string length.Code Snippets
let StringOfLengthConstructor<'c> (length : int) (defaultConstructor : string -> 'c) (input : string) =
match input with
| x when x <> null && x.Length = length -> Some (defaultConstructor input)
| _ -> None
type String3 = String3 of string
let String3 = StringOfLengthConstructor 3 String3Context
StackExchange Code Review Q#54713, answer score: 2
Revisions (0)
No revisions yet.