Reputation: 2077
I am trying to have a function that returns either one type or another. Is there any way in F# to encode this without creating a new discriminated union type and returning that discriminated union from the function?
Here is a simple example that will not compile:
type Json = JNumber of float
| JString of string
| JArray of seq<Json>
| JObject of Map<string, Json>
| JBool of bool
| JNull
let parseJson(jason:Json) = match jason with
|JNumber num -> num
|JString str -> str
|JArray arr -> arr |> Seq.map (fun e -> parseJson e)
|JObject obj -> obj |> Seq.map (fun (k,v) -> (k, parseJson v)) |> Map.ofArray
|JBool boo -> boo
|JNull -> None
Essentially I want to be able to turn a Json object into F# datastructures. (For some background I'm writing a toy json parser that converts text -> Json object -> F# datastructures in separate steps)
Upvotes: 0
Views: 126
Reputation: 623
That's not a good idea, in your case you pretty much want to return an union at this point. Think about how a function like that would be used, you couldn't pattern match.
For a function like that to work, you could cast every single value to obj with box
, but you would be trapped into casting every time you would need to use your parseJson function It would work, but it would not be good.
I'm talking about something like this: https://stackoverflow.com/a/2994300/1485641
Upvotes: 1