1

I've got a problem for which I am not sure which data-type to use. Currently I have gone for Array2D<'T>, but I may change my mind in the future to use another container. In C++ I would be using instance methods, and I could use a typedef which I could change at any point (so long as my new container supported all the required methods). This would provide a clean abstraction layer allowing me to change as I see fit.

How might I do something similarly in F#? Is there any use for typedef? Is this what one would use Haskell's 'higher kinded types' for?

Max Tilley
  • 1,509
  • 3
  • 10
  • 9
  • I think the problem in .NET is that it's hard to find types with the same methods. I did an initial effort in [this project](https://github.com/gmpl/FSharpPlus/blob/bb60400df656bf848a0de2d4503783b4b034b773/src/FSharpPlus/Operators.fs#L250) (see Collections and Foldable) in order to be able to switch between implementations. This technique is similar to Haskell's typeclasses. – Gus Jan 01 '17 at 00:45

1 Answers1

2

Type abbreviations could work if all methods in use are the same in abbreviated types

type MyType<'T> = Array2D<'T>

You could use MyType<'T> everywhere and then replace actual implementation. Abbreviations are erased at compile time.

Though, as Gustavo said in the comment, in .NET the same methods are not that common on types/classes unless they are derived from the same base type/class or implement the same interface - then it is more natural to use interfaces directly.

V.B.
  • 6,236
  • 1
  • 33
  • 56
  • I guess I was thinking more about the functional style where I wouldn't necessarily be using instance methods. – Max Tilley Feb 07 '14 at 17:51
  • I know that one could open another module to redefine operators (see here http://stackoverflow.com/questions/2271198/f-checked-arithmetics-scope), but haven't tried and do not know if that works for other static methods. Higher-order functions also come to mind, depending on what exactly you want to achieve. – V.B. Feb 07 '14 at 18:02