HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Defining a zip code string

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
codezipstringdefining

Problem

I'm following this

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 String5


or

type ZipCode = | Us of String5*(String4 option) | Canadian of String3*String3

Solution

The solution can be made cleaner by re-arranging the order of the arguments and using pointfree style.

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 String3


However, 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 String3

Context

StackExchange Code Review Q#54713, answer score: 2

Revisions (0)

No revisions yet.