What is the best way to create an exception that contains a type it is thrown from in F#? The following does not work:
// this fails since HeaderInfo is not yet defined. Can't seem use the and-keyword
// on HeaderInfo
exception MissingHeader of string*HeaderInfo
type HeaderInfo =
{
DefaultHeaderIndices: Map<string, int>;
AdditionalStudyIndices: Map<string, int>;
VolumeIndex: int option;
}
with member this.GetCommonIndex(name) =
match this.DefaultHeaderIndices.TryFind(name) with
| Some(idx) -> idx
| None ->
match this.AdditionalStudyIndices.TryFind(name) with
| Some(idx) -> idx
| None ->
match this.VolumeIndex with
| Some(idx) when name = optionalHeader -> idx
| _ -> raise <| MissingHeader(name, this)
Thanks!
You can use type extensions to add members to a type that was declared earlier. When you use type extension within the same module, the member is compiled as an ordinary (instance) member of the type, so it means exactly the same thing as ordinary member.
This way, you can first declare
HeaderInfo, then declaremissingHeaderand then add the memberGetCommonIndexto theHeaderInfotype.EDIT: I think you can also make the code a bit nicer using active patterns (although it is a slightly subtle use)