How to use out attributes in an F# Interface? - f#

I would like to define one of my parameters to be a C# out parameter in one of my interfaces. I realize that F# supports byref but how can I apply the System.Runtime.InteropServices.OutAttribute to one of my interface parameters?
C# Interface I am trying to replicate
public interface IStatisticalTests
{
void JohansenWrapper(
double[,] dat,
double alpha,
bool doAdfPreTests,
out double cointStatus,
out JohansenModelParameters[] johansenModelParameters);
}

Here's an example:
open System
open System.Runtime.InteropServices
[<Interface>]
type IPrimitiveParser =
//
abstract TryParseInt32 : str:string * [<Out>] value:byref<int> -> bool
[<EntryPoint>]
let main argv =
let parser =
{ new IPrimitiveParser with
member __.TryParseInt32 (str, value) =
let success, v = System.Int32.TryParse str
if success then value <- v
success
}
match parser.TryParseInt32 "123" with
| true, value ->
printfn "The parsed value is %i." value
| false, _ ->
printfn "The string could not be parsed."
0 // Success
Here's your interface, translated:
[<Interface>]
type IStatisticalTests =
//
abstract JohansenWrapper :
dat:float[,] *
alpha:float *
doAdfPreTests:bool *
[<Out>] cointStatus:byref<float> *
[<Out>] johansenModelParameters:byref<JohansenModelParameters[]>
-> unit

Related

Cast error (Type constraint missmatch)

I have problem with casting
type IConfig = interface end
type test(num: string) =
interface IConfig
member this.num = num
type init(context:string) =
interface IConfig
member this.context = context
let dict:Dictionary<string, IConfig> = new Dictionary<string, IConfig>()
dict.Add("x1", new test() { num = "1" });
dict.Add("x2", new init() { context = "1" });
for item in dict do
if(item.Key = "x1") then
let x = (item.Value :> init).context
//Here I have an error: Type constraint missmach. The type IConfig is not compatibile with type InitConfig
I've done the same with C#, and it works.
Please, help.
I had to make some changes to your code to get it working, but I think you're looking for the :?> operator instead of the :> operator. The :> only does upcasting (i.e. init -> IConfig), whereas :?> does downcasting (i.e. IConfig -> init), which is what you're trying to do here.
Here's the code I used to get it working:
open System.Collections.Generic
type IConfig = interface end
type test(num: string) =
interface IConfig
member this.num = num
type init(context:string) =
interface IConfig
member this.context = context
let dict:Dictionary<string, IConfig> = new Dictionary<string, IConfig>()
dict.Add("x1", new test(num = "1"))
dict.Add("x2", new init(context = "1"))
for item in dict do
if(item.Key = "x2") then
let x = (item.Value :?> init).context
printfn "%A" x

F# Error compiling

I have the following F# Code that is causing a compile error:
persistence.fs(32,21): error FS0072: Lookup on object of indeterminate type based on information prior to this program point. A type annotation may be needed prior to this program point to constrain the type of the object. This may allow the lookup to be resolved.
The error is at the line "serializer.write...."
Any help would be appreciated.
namespace persisitence
open System.Collections.Generic
open System
open System.IO
type LocalData<'T> =
struct
val mutable elements_ : 'T list
val mutable lock_ : obj
new(e: 'T list) = { elements_ = e ; lock_ = new obj() }
end
type BinaryPersistenceOut<'T, ^W when ^W: (member write : ('T * BinaryWriter) -> unit)>(fn: string, serializer: ^W) as this =
let writer_ = new BinaryWriter(File.Open(fn, FileMode.Append))
let mutable localdata_ = new LocalData<'T>([])
let serializer_ = serializer
let NUM_SECS_IN_MIN = 60
let NUM_MSECS_IN_SEC = 1000
let NUM_MIN_BETWEEN_COMMITS = 2
let TIME_TO_WAIT = 15
let closed_ = false
let freq_ = NUM_MIN_BETWEEN_COMMITS * NUM_SECS_IN_MIN * NUM_MSECS_IN_SEC
let path_ = fn
let timer_ = new System.Timers.Timer((float) (NUM_MIN_BETWEEN_COMMITS * NUM_MSECS_IN_SEC) )
let writetofile =
fun (arg: Timers.ElapsedEventArgs ) ->
lock localdata_.lock_ ( fun () ->
if closed_ = false then
for elem in localdata_.elements_ do
serializer.write(elem, writer_)
)
do
timer_.Elapsed.Add(writetofile)
Although it'd be nice if you could invoke the write function like serializer.write(elem, writer_), you can't. You have to invoke it like this instead:
(^W: (member write : ('T * BinaryWriter) -> unit) (serializer, (elem, writer_)))
Full code block:
type BinaryPersistenceOut<'T, ^W when ^W: (member write : ('T * BinaryWriter) -> unit)> (fn: string, serializer: ^W) as this =
let writer_ = new BinaryWriter(File.Open(fn, FileMode.Append))
let mutable localdata_ = new LocalData<'T>([])
let serializer_ = serializer
let NUM_SECS_IN_MIN = 60
let NUM_MSECS_IN_SEC = 1000
let NUM_MIN_BETWEEN_COMMITS = 2
let TIME_TO_WAIT = 15
let closed_ = false
let freq_ = NUM_MIN_BETWEEN_COMMITS * NUM_SECS_IN_MIN * NUM_MSECS_IN_SEC
let path_ = fn
let timer_ = new System.Timers.Timer((float) (NUM_MIN_BETWEEN_COMMITS * NUM_MSECS_IN_SEC) )
let writetofile =
fun (arg: Timers.ElapsedEventArgs ) ->
lock localdata_.lock_ ( fun () ->
if closed_ = false then
for elem in localdata_.elements_ do
(^W: (member write : ('T * BinaryWriter) -> unit) (serializer, (elem, writer_)))
)
do
timer_.Elapsed.Add(writetofile)
Caveat: this compiles, but I have no idea if it does what you want it to do.

The F# equivalent of C#'s 'out'

I am rewriting a C# library to F# and I need to translate the following code
bool success;
instance.GetValue(0x10, out success);
what is the equivalent of the out keyword in F#?
Neither wasatz's answer nor Max Malook's is complete. There are three ways of calling methods with out parameters. The second and third ways also work with ref parameters.
For the examples, assume the following type:
open System.Runtime.InteropServices //for OutAttribute
type SomeType() =
member this.GetValue (key, [<Out>] success : bool byref) =
if key = 10 then
success <- true
"Ten"
else
success <- false
null
Assume also that we have an instance of that type:
let o = SomeType()
Option 1
You can let the F# compiler handle the out parameter by tupling it with the return value:
let result1, success1 = o.GetValue 10
let result2, success2 = o.GetValue 11
Running the above lines in F# interactive yields
val success1 : bool = true
val result1 : string = "Ten"
val success2 : bool = false
val result2 : string = null
Option 2
You can use a mutable value, passing its address with the & operator:
let mutable success3 = false
let result3 = o.GetValue (10, &success3)
let mutable success4 = false
let result4 = o.GetValue (11, &success4)
In F# interactive, the result is
val mutable success3 : bool = true
val result3 : string = "Ten"
val mutable success4 : bool = false
val result4 : string = null
This option is best when you are delegating to another method, since you can pass the calling method's out parameter directly to the called method. For example, if you are implementing a wrapper around IDictionary<_,_>, you can code the TryGetValue method as
//...
interface IDictionary<'TKey, 'TValue> with
member this.TryGetValue (key, value) = inner.TryGetValue (key, &value)
//...
Option 3
You can use a reference cell:
let success5 = ref false
let result5 = o.GetValue (10, success5)
let success6 = ref false
let result6 = o.GetValue (11, success6)
The output:
val success5 : bool ref = {contents = true;}
val result5 : string = "Ten"
val success6 : bool ref = {contents = false;}
val result6 : string = null
Warning!
Be careful not to use the ref keyword as you would in C# for an in/out parameter. For example, the following does not yield the desired result:
let success7 = false
let result7 = o.GetValue (10, ref success7)
The output:
val success7 : bool = false
val result7 : string = "Ten"
Why does success7 hold the value false? Because success7 is an immutable variable.
In C#, ref calls attention to the fact that you are passing a reference to a variable as the argument for a ref parameter. It simply serves as insurance that the programmer of the caller is aware that the variable may be modified by the called method. In F# however, ref creates a new reference cell holding a copy of the value of the following expression.
In this case, we are making a reference cell that holds the value copied from the success7 variable, but not assigning that new reference cell to any variable. We then pass that reference cell to the GetValue method, which modifies the content of the reference cell. Because the calling method has no variable pointing to the modified cell, it has no way of reading the new value of the reference cell.
You should probably return an option or a tuple instead. Because F# has pattern matching you really don't need out parameters since there are better ways to return more than one value from a function.
So, something like this would be more idiomatic
let (value, success) = instance.GetValue(0x10)
where instance.GetValue is a
unit -> ('a, bool)
Or you could return an option and do something like
match instance.GetValue(0x10) with
| Some value -> doStuff value
| None -> failwith "Oops!"
You have to use a reference cell.
let success = ref false
instance.GetValue(0x10, success)
// access the value
!success
I think it's also worth mentioning here that the value of the out parameter doesn't have to be initialized.
It is possible to do the following:
let mutable success3 = Unchecked.defaultof<bool>
let result3 = o.GetValue (10, &success3)
This might be usefull in scenarios where you are calling a .NET library function with arrays as output parameters, i.e:
let mutable currFeatures = Unchecked.defaultof<PointF[]>
let mutable status = Unchecked.defaultof<byte[]>
let mutable trackError = Unchecked.defaultof<float32[]>
CvInvoke.CalcOpticalFlowPyrLK(
previousFrame,
nextFrame,
previousPoints,
Size(15,15),
2,
MCvTermCriteria(10, 0.03),
//Out params
&currFeatures,
&status,
&trackError,
//---------
LKFlowFlag.UserInitialFlow)

f# overwrite array access operator .[]

in F#, I want to make a type of indexed array, so I can access the element by either .[i] or .[index_names] and by slice notation with index .. Is it possible to overwrite .[] like this? thanks.
define overloaded indexer in your type:
type MyIndexedArray<'T>() =
member this.Item(i : int) : 'T = Unchecked.defaultof<_>
member this.Item(name : string) : 'T = Unchecked.defaultof<_>
member this.GetSlice(a : int option, b : int option) : 'T = Unchecked.defaultof<_>
let arr = new MyIndexedArray<int>()
let a = arr.[1]
let b = arr.["name"]
let c = arr.[1..2]
let d = arr.[1..]
let e = arr.[..3]
let f = arr.[*]

How to consume BlockingCollection<'a>.TryTake in F#

How do I go about using the TryTake method on a BlockingCollection<'a> passing in a timeout period in milliseconds?
Heres the signature:
BlockingCollection.TryTake(item: byref, millisecondsTimeout: int) : bool
is it possible to use the Tuple method of avoiding passing a ref type like on the Dictionary.TryGet methods?
i.e.
let success, item = myDictionary.TryGetValue(client)
Im struggling with this particular signature, any suggestions would be great.
Cheers!
I believe that you can only use that technique for byref parameters which occur at the end of the parameter list (this is similar to the rule for optional parameters). So if BlockingCollection.TryTake were defined with signature int * 'T byref -> bool it would work, but since it's defined as 'T byref * int -> bool it won't.
For example:
open System.Runtime.InteropServices
type T =
static member Meth1(a:int, [<Out>]b:string byref, [<Out>]c:bool byref) : char =
b <- sprintf "%i" a
c <- a % 2 = 0
char a
static member Meth2([<Out>]b:string byref, [<Out>]c:bool byref, a:int) : char =
b <- sprintf "%i" a
c <- a % 2 = 0
char a
// ok
let (r,b,c) = T.Meth1(5)
// ok
let (r,c) = T.Meth1(5,ref "test")
// ok
let r = T.Meth1(5, ref "test", ref true)
// doesn't compile
let (r,b,c) = T.Meth2(5)
// doesn't compile
let (r,c) = T.Meth2(ref "test", 5)
// ok
let r = T.Meth2(ref "test", ref true, 5)

Resources