How Can I Restrict the Usage of an F# Union Type to A Particular Option












2














I am teaching myself F#--For Fun and Profit!--and, while I've made some strides, I have run into a stumbling block with usage of algebraic types. Below is a JSON type that I coded to serialize an arbitrary JSON structure to a string. I am open to subjective comments on it's design and efficiency, of course, but I am mainly focussed on line 7:



type JSON =
| JString of string
| JNumber of decimal
| JBool of bool
| JNull
| JArray of JSON list
| JObject of Map< JSON, JSON >
with
member this.Serialize =
let rec serialize ( element : JSON ) =
match element with
| JString str ->
""" + str + """
| JNumber num ->
num.ToString()
| JBool bln ->
bln.ToString().ToLower()
| JNull ->
"null"
| JArray ary ->
"[" + String.concat "," ( List.map serialize ary ) + "]"
| JObject obj ->
"{" + (
Map.fold (
fun state key value ->
state + ( match state with "" -> "" | _ -> "," )
+ ( serialize key )
+ ":"
+ ( serialize value ) ) "" obj ) + "}"
serialize( this )


Anyone familiar with JSON knows that a key/value pair of a JSON object should be keyed on a string, not just any JSON element/value. Is there a way to further restrict the first type parameter of the Map? These, of course, do not work:



type JSON =
... elided ...
| JObject of Map< JSON.JString, JSON >


...



type JSON =
... elided ...
| JObject of Map< JString, JSON >


...



type JSON =
... elided ...
| JObject of Map< string, JSON >


Thanks.










share|improve this question


















  • 2




    JObject of Map< string, JSON > works on my computer...
    – Ringil
    Nov 12 at 18:33










  • I'll look into using string as the key again. I was having issues in the serialization of JObject with that. Thanks.
    – David Clark
    Nov 12 at 21:00
















2














I am teaching myself F#--For Fun and Profit!--and, while I've made some strides, I have run into a stumbling block with usage of algebraic types. Below is a JSON type that I coded to serialize an arbitrary JSON structure to a string. I am open to subjective comments on it's design and efficiency, of course, but I am mainly focussed on line 7:



type JSON =
| JString of string
| JNumber of decimal
| JBool of bool
| JNull
| JArray of JSON list
| JObject of Map< JSON, JSON >
with
member this.Serialize =
let rec serialize ( element : JSON ) =
match element with
| JString str ->
""" + str + """
| JNumber num ->
num.ToString()
| JBool bln ->
bln.ToString().ToLower()
| JNull ->
"null"
| JArray ary ->
"[" + String.concat "," ( List.map serialize ary ) + "]"
| JObject obj ->
"{" + (
Map.fold (
fun state key value ->
state + ( match state with "" -> "" | _ -> "," )
+ ( serialize key )
+ ":"
+ ( serialize value ) ) "" obj ) + "}"
serialize( this )


Anyone familiar with JSON knows that a key/value pair of a JSON object should be keyed on a string, not just any JSON element/value. Is there a way to further restrict the first type parameter of the Map? These, of course, do not work:



type JSON =
... elided ...
| JObject of Map< JSON.JString, JSON >


...



type JSON =
... elided ...
| JObject of Map< JString, JSON >


...



type JSON =
... elided ...
| JObject of Map< string, JSON >


Thanks.










share|improve this question


















  • 2




    JObject of Map< string, JSON > works on my computer...
    – Ringil
    Nov 12 at 18:33










  • I'll look into using string as the key again. I was having issues in the serialization of JObject with that. Thanks.
    – David Clark
    Nov 12 at 21:00














2












2








2







I am teaching myself F#--For Fun and Profit!--and, while I've made some strides, I have run into a stumbling block with usage of algebraic types. Below is a JSON type that I coded to serialize an arbitrary JSON structure to a string. I am open to subjective comments on it's design and efficiency, of course, but I am mainly focussed on line 7:



type JSON =
| JString of string
| JNumber of decimal
| JBool of bool
| JNull
| JArray of JSON list
| JObject of Map< JSON, JSON >
with
member this.Serialize =
let rec serialize ( element : JSON ) =
match element with
| JString str ->
""" + str + """
| JNumber num ->
num.ToString()
| JBool bln ->
bln.ToString().ToLower()
| JNull ->
"null"
| JArray ary ->
"[" + String.concat "," ( List.map serialize ary ) + "]"
| JObject obj ->
"{" + (
Map.fold (
fun state key value ->
state + ( match state with "" -> "" | _ -> "," )
+ ( serialize key )
+ ":"
+ ( serialize value ) ) "" obj ) + "}"
serialize( this )


Anyone familiar with JSON knows that a key/value pair of a JSON object should be keyed on a string, not just any JSON element/value. Is there a way to further restrict the first type parameter of the Map? These, of course, do not work:



type JSON =
... elided ...
| JObject of Map< JSON.JString, JSON >


...



type JSON =
... elided ...
| JObject of Map< JString, JSON >


...



type JSON =
... elided ...
| JObject of Map< string, JSON >


Thanks.










share|improve this question













I am teaching myself F#--For Fun and Profit!--and, while I've made some strides, I have run into a stumbling block with usage of algebraic types. Below is a JSON type that I coded to serialize an arbitrary JSON structure to a string. I am open to subjective comments on it's design and efficiency, of course, but I am mainly focussed on line 7:



type JSON =
| JString of string
| JNumber of decimal
| JBool of bool
| JNull
| JArray of JSON list
| JObject of Map< JSON, JSON >
with
member this.Serialize =
let rec serialize ( element : JSON ) =
match element with
| JString str ->
""" + str + """
| JNumber num ->
num.ToString()
| JBool bln ->
bln.ToString().ToLower()
| JNull ->
"null"
| JArray ary ->
"[" + String.concat "," ( List.map serialize ary ) + "]"
| JObject obj ->
"{" + (
Map.fold (
fun state key value ->
state + ( match state with "" -> "" | _ -> "," )
+ ( serialize key )
+ ":"
+ ( serialize value ) ) "" obj ) + "}"
serialize( this )


Anyone familiar with JSON knows that a key/value pair of a JSON object should be keyed on a string, not just any JSON element/value. Is there a way to further restrict the first type parameter of the Map? These, of course, do not work:



type JSON =
... elided ...
| JObject of Map< JSON.JString, JSON >


...



type JSON =
... elided ...
| JObject of Map< JString, JSON >


...



type JSON =
... elided ...
| JObject of Map< string, JSON >


Thanks.







generics f# algebraic-data-types discriminated-union






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 12 at 17:46









David Clark

345




345








  • 2




    JObject of Map< string, JSON > works on my computer...
    – Ringil
    Nov 12 at 18:33










  • I'll look into using string as the key again. I was having issues in the serialization of JObject with that. Thanks.
    – David Clark
    Nov 12 at 21:00














  • 2




    JObject of Map< string, JSON > works on my computer...
    – Ringil
    Nov 12 at 18:33










  • I'll look into using string as the key again. I was having issues in the serialization of JObject with that. Thanks.
    – David Clark
    Nov 12 at 21:00








2




2




JObject of Map< string, JSON > works on my computer...
– Ringil
Nov 12 at 18:33




JObject of Map< string, JSON > works on my computer...
– Ringil
Nov 12 at 18:33












I'll look into using string as the key again. I was having issues in the serialization of JObject with that. Thanks.
– David Clark
Nov 12 at 21:00




I'll look into using string as the key again. I was having issues in the serialization of JObject with that. Thanks.
– David Clark
Nov 12 at 21:00












1 Answer
1






active

oldest

votes


















5














Referencing another case identifier from within a discriminated union is not possible. From Discriminated Unions,




Syntax



[ attributes ]



type [accessibility-modifier] type-name =



    | case-identifier1 [of [ fieldname1 : ] type1 [ * [ fieldname2 : ] type2 ...]



    | case-identifier2 [of [fieldname3 : ] type3 [ * [ fieldname4 : ] type4 ...]



    [ member-list ]




This means that each case identifier must be of some type. A case identifier itself is not a type.



One way you could achieve the same functionality is by breaking the discriminated union into multiple discriminated unions:



type JSONKey =
| JString of string

type JSONValue =
| JString of string
| JNumber of decimal
| JBool of bool
| JNull
| JArray of JSONValue list
| JObject of Map<JSONKey, JSONValue>


and then defining JSON as:



type JSON = Map<JSONKey, JSONValue>


Then, serialize would need to be changed to let rec serialize ( element : JSONValue )
and
serialize( this ) would need to be changed to serialize( JObject this ).





As @Ringil mentioned, Map<string, JSON> will work in this situation, but this is not too extensible/restrictive.






share|improve this answer



















  • 2




    The case identifier NOT being a type is a distinction that was lost on me at this juncture. I was more or less thinking of them as subtypes. I appreciate the clarification and suggested solution.
    – David Clark
    Nov 12 at 21:01











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53267472%2fhow-can-i-restrict-the-usage-of-an-f-union-type-to-a-particular-option%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









5














Referencing another case identifier from within a discriminated union is not possible. From Discriminated Unions,




Syntax



[ attributes ]



type [accessibility-modifier] type-name =



    | case-identifier1 [of [ fieldname1 : ] type1 [ * [ fieldname2 : ] type2 ...]



    | case-identifier2 [of [fieldname3 : ] type3 [ * [ fieldname4 : ] type4 ...]



    [ member-list ]




This means that each case identifier must be of some type. A case identifier itself is not a type.



One way you could achieve the same functionality is by breaking the discriminated union into multiple discriminated unions:



type JSONKey =
| JString of string

type JSONValue =
| JString of string
| JNumber of decimal
| JBool of bool
| JNull
| JArray of JSONValue list
| JObject of Map<JSONKey, JSONValue>


and then defining JSON as:



type JSON = Map<JSONKey, JSONValue>


Then, serialize would need to be changed to let rec serialize ( element : JSONValue )
and
serialize( this ) would need to be changed to serialize( JObject this ).





As @Ringil mentioned, Map<string, JSON> will work in this situation, but this is not too extensible/restrictive.






share|improve this answer



















  • 2




    The case identifier NOT being a type is a distinction that was lost on me at this juncture. I was more or less thinking of them as subtypes. I appreciate the clarification and suggested solution.
    – David Clark
    Nov 12 at 21:01
















5














Referencing another case identifier from within a discriminated union is not possible. From Discriminated Unions,




Syntax



[ attributes ]



type [accessibility-modifier] type-name =



    | case-identifier1 [of [ fieldname1 : ] type1 [ * [ fieldname2 : ] type2 ...]



    | case-identifier2 [of [fieldname3 : ] type3 [ * [ fieldname4 : ] type4 ...]



    [ member-list ]




This means that each case identifier must be of some type. A case identifier itself is not a type.



One way you could achieve the same functionality is by breaking the discriminated union into multiple discriminated unions:



type JSONKey =
| JString of string

type JSONValue =
| JString of string
| JNumber of decimal
| JBool of bool
| JNull
| JArray of JSONValue list
| JObject of Map<JSONKey, JSONValue>


and then defining JSON as:



type JSON = Map<JSONKey, JSONValue>


Then, serialize would need to be changed to let rec serialize ( element : JSONValue )
and
serialize( this ) would need to be changed to serialize( JObject this ).





As @Ringil mentioned, Map<string, JSON> will work in this situation, but this is not too extensible/restrictive.






share|improve this answer



















  • 2




    The case identifier NOT being a type is a distinction that was lost on me at this juncture. I was more or less thinking of them as subtypes. I appreciate the clarification and suggested solution.
    – David Clark
    Nov 12 at 21:01














5












5








5






Referencing another case identifier from within a discriminated union is not possible. From Discriminated Unions,




Syntax



[ attributes ]



type [accessibility-modifier] type-name =



    | case-identifier1 [of [ fieldname1 : ] type1 [ * [ fieldname2 : ] type2 ...]



    | case-identifier2 [of [fieldname3 : ] type3 [ * [ fieldname4 : ] type4 ...]



    [ member-list ]




This means that each case identifier must be of some type. A case identifier itself is not a type.



One way you could achieve the same functionality is by breaking the discriminated union into multiple discriminated unions:



type JSONKey =
| JString of string

type JSONValue =
| JString of string
| JNumber of decimal
| JBool of bool
| JNull
| JArray of JSONValue list
| JObject of Map<JSONKey, JSONValue>


and then defining JSON as:



type JSON = Map<JSONKey, JSONValue>


Then, serialize would need to be changed to let rec serialize ( element : JSONValue )
and
serialize( this ) would need to be changed to serialize( JObject this ).





As @Ringil mentioned, Map<string, JSON> will work in this situation, but this is not too extensible/restrictive.






share|improve this answer














Referencing another case identifier from within a discriminated union is not possible. From Discriminated Unions,




Syntax



[ attributes ]



type [accessibility-modifier] type-name =



    | case-identifier1 [of [ fieldname1 : ] type1 [ * [ fieldname2 : ] type2 ...]



    | case-identifier2 [of [fieldname3 : ] type3 [ * [ fieldname4 : ] type4 ...]



    [ member-list ]




This means that each case identifier must be of some type. A case identifier itself is not a type.



One way you could achieve the same functionality is by breaking the discriminated union into multiple discriminated unions:



type JSONKey =
| JString of string

type JSONValue =
| JString of string
| JNumber of decimal
| JBool of bool
| JNull
| JArray of JSONValue list
| JObject of Map<JSONKey, JSONValue>


and then defining JSON as:



type JSON = Map<JSONKey, JSONValue>


Then, serialize would need to be changed to let rec serialize ( element : JSONValue )
and
serialize( this ) would need to be changed to serialize( JObject this ).





As @Ringil mentioned, Map<string, JSON> will work in this situation, but this is not too extensible/restrictive.







share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 12 at 18:41

























answered Nov 12 at 18:31









ljeabmreosn

573520




573520








  • 2




    The case identifier NOT being a type is a distinction that was lost on me at this juncture. I was more or less thinking of them as subtypes. I appreciate the clarification and suggested solution.
    – David Clark
    Nov 12 at 21:01














  • 2




    The case identifier NOT being a type is a distinction that was lost on me at this juncture. I was more or less thinking of them as subtypes. I appreciate the clarification and suggested solution.
    – David Clark
    Nov 12 at 21:01








2




2




The case identifier NOT being a type is a distinction that was lost on me at this juncture. I was more or less thinking of them as subtypes. I appreciate the clarification and suggested solution.
– David Clark
Nov 12 at 21:01




The case identifier NOT being a type is a distinction that was lost on me at this juncture. I was more or less thinking of them as subtypes. I appreciate the clarification and suggested solution.
– David Clark
Nov 12 at 21:01


















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.





Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


Please pay close attention to the following guidance:


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53267472%2fhow-can-i-restrict-the-usage-of-an-f-union-type-to-a-particular-option%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Xamarin.iOS Cant Deploy on Iphone

Glorious Revolution

Dulmage-Mendelsohn matrix decomposition in Python