Construct generic function - f#

I have a type:
type DictionaryCache<'a, 'b when 'a :comparison>()
And I have another type which contains some of this DictionaryCache:
type Cache() =
let user = new DictionaryCache<int, User>()
let userByLogin = new DictionaryCache<string, User>()
member this.User = user
member this.UserByLogin = userByLogin
In the last type I want to create generic function which will return one of the members based on input parameter:
member this.CacheNameToDictionary (cacheName: string) : DictionaryCache<'a, 'b> option =
match cacheName with
| "userByAutoincrementedId" -> Some(this.User)
| "userByLogin" -> Some(this.UserByLogin)
| _ -> None
But it doesn't work because of type mismatch.
Is there any way to rewrite this function ?
Update: here is a full code what I need to do:
type Cache() =
let user = new DictionaryCache<int, User>()
let userByLogin = new DictionaryCache<string, User>()
static let mutable instance = lazy(new Cache())
static member Instance with get() = instance.Value
member this.User = user
member this.UserByLogin = userByLogin
member this.Get (useCache: string) (cacheName: string) (id: 'a) longFunction exceptionFunction : 'b option =
let nameToDictionary() : DictionaryCache<'a, 'b> option =
match cacheName with
| "userByAutoincrementedId" -> Some(this.User)
| "userByLogin" -> Some(this.UserByLogin)
| _ -> None
let foo() : 'b option =
try
longFunction()
with
| exn -> exceptionFunction exn
None
match (useCache, nameToDictionary()) with
| "true", Some(dictionary) ->
match dictionary.Get id with
| Some(result) -> Some(result)
| _ -> match foo() with
| Some(result) -> dictionary.Put id result
Some(result)
| _ -> None
| _ -> foo()

This is not possible - the problem is that the return type of the method would depend on the string that it gets as the input argument. The input string is only known at run-time, but the type needs to be known at compile-time.
You could use the Choice type which lets you return one of multiple different types:
member this.CacheNameToDictionary (cacheName: string) =
match cacheName with
| "userByAutoincrementedId" -> Choice1Of3(this.User)
| "userByLogin" -> Choice2Of3(this.UserByLogin)
| _ -> Choice3Of3()
This works, but the return type lists all three alternatives and is pretty ugly:
Choice<DictionaryCache<int,User>, DictionaryCache<string,User>,unit>
Also, the consumer of this method will have to pattern match on the result and handle the two different dictionaries in different ways, so this might not make your code particularly beautiful.
Honestly, I think that you are adding a level of abstraction that you do not need. If there are two different keys, then you need different code to handle that and it's unlikely that you'll be able to write code that is extensible and adds third kind of dictionary.

Related

Casting a system.Object to a specific type in F#

I have a standard type that I use to pass messages and objects between functions that has an optional MessageObject that is System.Object.
type StatusMessage = {
Message: string
MessageObject: Object option
Success: bool
}
In the following specific function - I know that the Message Object will always contain the following specific type and I want to be able to access that within the function
type SingleCorrectRecord = {
CardTransactionWithOrder: CardWithOrder
Line: RowTransaction
ExchangeVariance: decimal
}
My function is:
let getEstimatedVariance(matchedTransactions: StatusMessage list): decimal =
let exchangeVariance:decimal =
matchedTransactions |> Seq.sumBy(fun mt -> mt.MessageObject.ExchangeVariance)
estimatedVariance
Obviously mt.MessageObject doesn't contain the property "ExchangeVariance" but I need to be able to cast (or unbox?) the object so that it knows that it is a SingleCorrectRecord type and I can access the properties.
Any help is appreciated.
You can nest the dynamic type test with the union case pattern in the same match expression:
let exchangeVariance =
matchedTransactions |> Seq.sumBy (fun mt ->
match mt.MessageObject with
| Some(:? SingleCorrectRecord as scr) -> scr.ExchangeVariance
| _ -> 0M )
// val exchangeVariance : decimal
:?> is the downcast operator (or :? within pattern matching) which can be used for this problem. However, it is typically not recommended to use downcasting, which can fail at runtime, in F# code.
As an alternative, you could structure your StatusMessage type to be generic or to use a discriminated union depending on whether messages with different payload types need to be stored in the same collection.
// This type can store any type of message however StatusMessage<SingleCorrectRecord> is
// a different type to StatusMessage<Other> and they can't be stored in the same collection.
type StatusMessage<'T> = {
Message: string
MessageObject: 'T option
Success: bool
}
let getEstimatedVariance(matchedTransactions: StatusMessage<SingleCorrectRecord> list): decimal =
let estimatedVariance:decimal =
matchedTransactions |> Seq.sumBy(fun mt ->
match mt.MessageObject with
| Some msg -> msg.ExchangeVariance
| None -> 0M )
estimatedVariance
If the messages need to be in a grouped collection you could define all messages in a MsgPayload discriminated union:
type MsgPayload =
| SingleCorrectRecord of SingleCorrectRecord
| Other of string
type StatusMessage2 = {
Message: string
MessageObject: MsgPayload option
Success: bool
}
let getEstimatedVariance2(matchedTransactions: StatusMessage2 list): decimal =
let estimatedVariance:decimal =
matchedTransactions |> Seq.sumBy(fun mt ->
match mt.MessageObject with
| Some (SingleCorrectRecord msg) -> msg.ExchangeVariance
| _ -> 0M )
estimatedVariance

Type inference workaround for generic function

Given the following parametric type
type SomeDU2<'a,'b> =
| One of 'a
| Two of 'a * 'b
I have to functions that check if the given param is the respective union case without regard to params
let checkOne x =
match x with
| One _ -> true
| _ -> false
let checkTwo x =
match x with
| Two _ -> true
| _ -> false
This works pretty nice and as expected
let oi = checkOne (One 1)
let os = checkOne (One "1")
let tis = checkTwo (Two (1, "1"))
let tsi = checkTwo (Two ("1", 1))
I can switch the types as I like.
Now However I like to combine those two functions into one creation function
let makeUC () = (checkOne, checkTwo)
and then instantiate like this
let (o,t) = makeUC ()
only it gives me this error message now
Value restriction. The value 'o' has been inferred to have generic type
val o : (SomeDU2<'_a,'_b> -> bool)
Either make the arguments to 'o' explicit or, if you do not intend for it to be generic, add a type annotation.
val o : (SomeDU2<obj,obj> -> bool)
Actually I dont want that - nor do I need that.
Probably its a instance of missing higher kinded types in F#
Is there a way around this?
Edit
Actually me question wasnt complety as per #johns comment below.
Obviously I can do the following
let ro1 = o ((One 1) : SomeDU2<int,int>)
let rt1 = t (Two (1,2))
which then will backwards infer o and t to be of type SomeDU2<int,int> -> bool (I find this backwards inference very strange thou). The problem then is that o wont allow for the below anymore.
let ro2 = o ((One "1") : SomeDU2<string,int>)
So I'd have to instantiate a specific o instance for every combination of generic parameters of SomeDU2.
You would run into the value restriction even without the tuple:
let o = (fun () -> checkOne)()
If you need the results of invoking a function to be applicable to values of any type, then one solution would be to create instances of a nominal type with a generic method:
type DU2Checker =
abstract Check : SomeDU2<'a,'b> -> bool
let checkOne = {
new DU2Checker with
member this.Check(x) =
match x with
| One _ -> true
| _ -> false }
let checkTwo = {
new DU2Checker with
member this.Check(x) =
match x with
| Two _ -> true
| _ -> false }
let makeUC() = checkOne, checkTwo
let o,t = makeUC()
let false = o.Check(Two(3,4))

Pattern matching based on the function signature

In F# can you pattern match on a function signature. I want to decorate a number of functions with a function that measures the execution of the function and calls out to statsd. The current function I have is:
let WrapFunctionWithPrefix(metrics:Metric.Client.IRecorder, functionToWrap, prefix) =
let metricsIdentifier = (sprintf "%s.%s" prefix Environment.MachineName)
using (metrics.StartTimer(metricsIdentifier)) ( fun metrics -> functionToWrap)
As you can see above, the prefix will vary, and in our application this will vary per function definition. So rather than having to pass in the measure prefix every time I want to do something like the following:
let WrapFunction metrics afunc =
match afunc with
| :? (int -> int) -> WrapFunctionWithPrefix(metrics, afunc, "My function 1")
| :? (string -> string) -> WrapFunctionWithPrefix(metrics, afunc, "My function 2")
| _ -> failwith "Unknown function def"
Is there any way of pattern matching based on the function signature in F#?
Any help appreciated.
Billy
Would it be possible to declare the cases as a DU?
type MyFunctions =
| Intish of int -> int
| Stringish of string -> string
let WrapFunction metrics afunc =
match box afunc with
| :? (int -> int) -> WrapFunctionWithPrefix(metrics, afunc, "My function 1")
| :? (string -> string) -> WrapFunctionWithPrefix(metrics, afunc, "My function 2")
| _ -> failwith "Unknown function def"
will work for your pattern match. You normally end up having to box unknown types before trying to cast them, as :? doesn't like being used on value types.
I'm not totally sure how your using statement will interact with the function you return though. I think it will dispose metrics and return the function immediately, which is probably not what you want.

F# How to have a value's type determined by a match statement?

Here is my problem:
let foo =
match bar with
| barConfig1 -> configType1(devices:DeviceEntities,DeviceStartIndex,inputStartIndex,outputStartIndex)
| barConfig2 -> configType2(devices:DeviceEntities,DeviceStartIndex,inputStartIndex,outputStartIndex)
| barConfig3 -> configType3(devices:DeviceEntities,DeviceStartIndex,inputStartIndex,outputStartIndex)
| barConfig4 -> configType4(devices:DeviceEntities,DeviceStartIndex,inputStartIndex,outputStartIndex)
I'd like to have the type of foo be determined by the match statement, but it always sets foo to the first type.
type bar =
|barConfig1
|barConfig2
|barConfig3
|barConfig4
In F#, there are no statements, only expressions, and each expression has to have a single concrete type. A match block is an expression as well, meaning that it has to have a single concrete type. What follows from that is that each case of the match has to have the same type as well.
That is, something like this is not valid F#:
let foo = // int? string?
match bar with // int? string?
| Int -> 3 // int
| String -> "Three" // string
In this case, the type inference mechanism will expect the type of the match to be the same as the type of the first case - int, and end up confused when it sees the string in the second. In your example the same thing happens - type inference expects all the cases to return a configType1.
A way around it would be by casting the values into a common supertype or interface type. So for your case, assuming the configTypes implement a common IConfigType interface:
let foo = // IConfigType
let arg = (devices:DeviceEntities,DeviceStartIndex,inputStartIndex,outputStartIndex)
match bar with
| barConfig1 -> configType1(arg) :> IConfigType
| barConfig2 -> configType2(arg) :> IConfigType
| barConfig3 -> configType3(arg) :> IConfigType
| barConfig4 -> configType4(arg) :> IConfigType
If the output type has a limited number of cases, you can make that a discriminated union as well:
type ConfigType =
| ConfigType1 of configType1
| ConfigType2 of configType2
| ConfigType3 of configType3
| ConfigType4 of configType4``
let foo =
match bar with
| barConfig1 -> ConfigType1 <| configType1(devices:DeviceEntities,DeviceStartIndex,inputStartIndex,outputStartIndex)
| barConfig2 -> ConfigType2 <| configType2(devices:DeviceEntities,DeviceStartIndex,inputStartIndex,outputStartIndex)
| barConfig3 -> ConfigType3 <| configType3(devices:DeviceEntities,DeviceStartIndex,inputStartIndex,outputStartIndex)
| barConfig4 -> ConfigType4 <| configType4(devices:DeviceEntities,DeviceStartIndex,inputStartIndex,outputStartIndex)``
Alternately, if they all implement an interface or inherit some base class, you can upcast to that, as with scrwtp's answer.

Understanding inference of discriminated unions

Consider the following code...
type TypeOne () =
member val Name = "" with get, set
type TypeTwo () =
member val Name = "" with get, set
member val Property = 0 with get, set
[<RequireQualifiedAccess>]
type UnionType =
| TypeOne of TypeOne
| TypeTwo of TypeTwo
// this only succeeds because we have defined the union type a
// requiring qualified access. otherwise TypeOne would be inferred
// as the union case, not the type (understandably)...
let t1 = TypeOne ()
// if we want t1 "as" the union type, we have to do the following...
let ut1 = UnionType.TypeOne t1
// the following function returns a result of type UnionType
// but we have to explicitly do this for each type
let makeUnion switch =
match switch with
| true -> UnionType.TypeOne (TypeOne ())
| _ -> UnionType.TypeTwo (TypeTwo ())
As in the comments, it seems like there's no way of inferring that return results should be of a union type, and if we have to require qualified access on the union type this is extremely verbose (which seems worryingly wrong).
There's also no way of creating a function that takes only the union types and returns them as the union. (In this case a function which takes a TypeOne or TypeTwo and returns UnionType). Or is there? Are there better ways of working with discriminated unions?
As pad has pointed out - you don't need to qualify a union case with its parent type - so you can write
let makeUnion switch =
match switch with
| true -> TypeOne (new TypeOne ())
| false -> TypeTwo (new TypeTwo ())
However you will always have to specify the TypeOne. This is to avoid the ambiguity present if you have multiple cases which take the same arguments - like
type foo=
|Bar of int
|Baz of int
Then even knowing the return type, the compiler can't work out what to return. A more common example is actually with cases which take no arguments - say you decide to redifine true and false:
type bool = |True |False
type TypeOne() =
member val Name = "" with get, set
type TypeTwo() =
member val Name = "" with get, set
member val Property = 0 with get, set
type UnionType =
| TypeOne of TypeOne
| TypeTwo of TypeTwo
/// You can give some hints to the type checker
/// by saying that you want a class constructor
let t1 = new TypeOne()
/// No need to use fully-qualified access on union types
let ut1 = TypeOne t1
let makeUnion switch =
match switch with
| true -> TypeOne (new TypeOne())
| false -> TypeTwo (new TypeTwo())

Resources