ceth
ceth

Reputation: 45295

Is it possible to use anonymous records

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 ?

Upvotes: 3

Views: 545

Answers (1)

Fyodor Soikin
Fyodor Soikin

Reputation: 80744

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" ]

Upvotes: 8

Related Questions