简体   繁体   中英

f# discriminated union generic

What is the syntax for a generic TryValue type that can return a Value of 'a or an Error of 'b?

type TryValue =
    | Value of 'a
    | Error of 'b

If error is a string then it's fine:

type 'a TryValue =
    | Value of 'a
    | Error of string

I'd like to define a tryRun function that takes an error creator, a function and a parameter that will try to run the function with the parameter and on any error use the error creator function to create an error:

let tryRun createErrorFn param fn =
    try 
        Value (fn param)
    with
        | ex  -> Error (createErrorFn ex.Message param)

And a wrapper for any function to be wrapped by a tryRun:

let wrapTryRun createErrorFn fn param =
    match param with
    | Value a -> tryRun createErrorFn a fn
    | Error e -> Error e

Now I can run a list of functions (pseudo code, have not yet fully worked this out):

let createErrorFn errorMessage param =
    URLProcessignError {url=param.url;errorMessage=errorMessage}
[fn1;fn2] |> List.fold (fun acc fn -> (wrapTryRun createErrorFn fn acc))

You are missing the generic parameters in the left side:

type TryValue<'a,'b> =
    | Value of 'a
    | Error of 'b

When it's only one parameter you can use the ML style as you did in the case of a string, but if you have more than one parameter you should use the .NET notation with the < > angle brackets.

Actually, the old ML style can also be used with more than one type parameter by specifying a tuple:

type ('a, 'b) TryValue =
    | Value of 'a
    | Error of 'b

However, I believe I read the old syntax is deprecated…

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