简体   繁体   中英

How return from a function a generic value in F#

I'm decoding a stream of json objects that are of different types:

type AppRow =
    | ZoneR of ZoneRow
    | CustomerR of CustomerRow

I need to return the decoded object:

//None work:
let fromJson x =
let fromJson x:'T =
let fromJson<'T> x =
let fromJson<'T> x:'T =
    Json.Compact.deserialize x

let decodeLog table json =
    match table with
    | "zone" ->
        fromJson json |> ZoneR
    | "customer" ->
        fromJson json |> CustomerR
    | _ -> failwith "Not ready yet"   

I can't figure how replicate the effect of :

public static T deserialize<T> (string json)
{
    return JsonConvert.DeserializeObject<T> (json, Compact.Internal.Settings.settings);
}

I don't wanna to call Json.Compact.deserialize because I'm abstracting the encodign/decoding and need to do some extra steps in fromJson

If you want to define a function that takes a string and has a generic return type then either of the following two should work (the latter lets you specify the type explicitly when calling the function, the former does not so the type needs to be inferred).

let fromJson x : 'T = ...
let fromJson<'T> x : 'T = ...

You can be more explicit and annotate x just to be clear:

let fromJson (x:string) : 'T = ...

When you say your code does not work, what exactly do you mean? The following is a simple silly example that only handles two values (rather than properly decoding JSON), but compiles fine and shows the syntax:

type AppRow =
    | ZoneR of int
    | CustomerR of string

let fromJson (x:string) : 'T =
    if x = "1" then unbox 1
    elif x = "hi" then unbox "hi"
    else failwith "wrong input"

let decodeLog table json =
    match table with
    | "zone" ->
        fromJson json |> ZoneR
    | "customer" ->
        fromJson json |> CustomerR
    | _ -> failwith "Not ready yet"  

decodeLog "zone" "1"
decodeLog "customer" "hi"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM