Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use anonymous records

Tags:

f#

I have a function which log exception and any record, which was the reason of exception:

let logExceptionWithObject(exn: exn) (obj: Object) =
    try
        delimiter()

        FSharpType.GetRecordFields (obj.GetType())
        |> Array.iter (fun f -> 
                        logger.Error(f.Name + " " + f.GetValue(obj).ToString())
                      )  

        logger.Error(exn.Message)
        logger.Verbose("{@Exn}", exn)
    with
        | exn -> Console.WriteLine(exn.Message)

I can call this function with any record which I have created type for. But sometimes I need to call this function with record I have no type declaration for:

logExceptionWithObject exn { A = 10; B = 20; C = "some" }

I don't want to declare type for each of such records, but the compiler gev me error:

The record label 'A' is not defined.

Is it possible to use anonymous records ?

like image 640
ceth Avatar asked Dec 03 '25 17:12

ceth


1 Answers

F# does not have anonymous records. But in your example, you don't need them anyway, because you're only using them as dictionaries, so why not use real dictionaries?

But wait, you don't even need a dictionary - all you need is just a list of key/value pairs, that's it.

let logExceptionWithObject(exn: exn) map =
    try
        delimiter()
        map |> Seq.iter ( fun (k, v) -> sprintf "%s %s" k v |> logger.Error )
        logger.Error(exn.Message)
        logger.Verbose("{@Exn}", exn)
    with
        | exn -> Console.WriteLine(exn.Message)

Usage:

logExceptionWithObject exn [ "A","10" ; "B","20" ; "C","some" ]
like image 83
Fyodor Soikin Avatar answered Dec 06 '25 11:12

Fyodor Soikin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!