Skip to content

Instantly share code, notes, and snippets.

@ruxo
Last active May 2, 2023 23:10
Show Gist options
  • Save ruxo/23084ef722725d6fdefcf1709284bea7 to your computer and use it in GitHub Desktop.
Save ruxo/23084ef722725d6fdefcf1709284bea7 to your computer and use it in GitHub Desktop.
Demonstrate ad-hoc polymorphism in F#. It uses inline function with Statically Resolved Type Parameters feature. Try it in [repl.it](https://replit.com/@ruxozheng/F-Ad-hoc-polymorphism)
// From: https://angrydexterous.github.io/typeclassish.html
type Num<'A> =
abstract member Add: 'A -> 'A -> 'A
abstract member Subtract: 'A -> 'A -> 'A
[<Struct; NoComparison; NoEquality>]
type TInt =
interface Num<int> with
member my.Add x y = x + y
member my.Subtract x y = x - y
[<Struct; NoComparison; NoEquality>]
type TFloat =
interface Num<float> with
member my.Add x y = x + y
member my.Subtract x y = x - y
[<Struct; NoComparison; NoEquality>]
type Num =
static member inline ($) (_: Num, _: int) = Unchecked.defaultof<TInt>
static member inline ($) (_: Num, _: float) = Unchecked.defaultof<TFloat>
let inline num (x: 'a) :^m when ^m :> Num<'a> = Unchecked.defaultof<Num> $ x
let inline doubleX x = (num x).Add x x
printfn $"Result = {doubleX 20}"
printfn $"Result = {doubleX 1.23}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment