1

Given:

let ab = ArgumentBlockSettingStore()
let a  = ab :> ISettingStore

Is there a way to define a prefix operator (~~) so that

let ab, a = ~~ArgumentBlockSettingStore() : _ * ISettingStore

becomes possible?

Cetin Sert
  • 4,497
  • 5
  • 38
  • 76
  • looks like I hit some compiler restrictions as described in: http://stackoverflow.com/questions/4561663/rewrite-some-c-sharp-generic-code-into-f – Cetin Sert Jan 15 '12 at 17:20

1 Answers1

2

I think you're hitting the compiler restrictions that you mentioned in the comment - you can't write the ~~ operator in a fully generic and safe way meaning that it will only allow casting to an interface that the argument implements. You can define an operator that will cast to any other type, but that's less safe:

let inline (~~) (a:^T) : ^T * ^R = a, (box a) :?> ^R

let reader, (disposable:IDisposable) = ~~(new StreamReader("..."))

I used inline, because the operator is quite simple, but it works the same way with normal operators. This compiles even if you use Random in the type annotation for disposable, which is a bit unfortunate.

Tomas Petricek
  • 240,744
  • 19
  • 378
  • 553
  • It is great to see that there's a way to do it albeit type-unsafe. Thanks a lot :) I guess I will not use it as I need such casting only in one place but I think it is a neat way to declare objects for use with all the various interfaces they may implement. Could also be extended to ~~~ for 1 type, 2 interfaces etc. – Cetin Sert Jan 16 '12 at 10:22