8 people like it.

Function overloading

I came up with a gimmick. It looks like function overloading.

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
16: 
17: 
18: 
type FunHolder<'Arg, 'Result>() =
    // F# 3.0
    //static member val Definition =
    //    Unchecked.defaultof<'Arg -> 'Result> with get, set
    // F# 2.0
    static let mutable definition = Unchecked.defaultof<'Arg -> 'Result>
    static member Definition with get()  = definition
                             and  set(x) = definition <- x

FunHolder.Definition <- fun x -> x * 2
FunHolder.Definition <- fun (x:string) -> x + x
FunHolder.Definition <- fun () -> (), ()

let twice<'a, 'b> = FunHolder<'a, 'b>.Definition

let x : int         = twice 10  // => 20
let y : string      = twice "X" // => "XX"
let z : unit * unit = twice ()  // => (null, null)
Multiple items
type FunHolder<'Arg,'Result> =
  new : unit -> FunHolder<'Arg,'Result>
  static member Definition : ('Arg -> 'Result)
  static member Definition : ('Arg -> 'Result) with set

Full name: Script.FunHolder<_,_>

--------------------
new : unit -> FunHolder<'Arg,'Result>
val mutable definition : ('Arg -> 'Result)
module Unchecked

from Microsoft.FSharp.Core.Operators
val defaultof<'T> : 'T

Full name: Microsoft.FSharp.Core.Operators.Unchecked.defaultof
static member FunHolder.Definition : ('Arg -> 'Result) with set

Full name: Script.FunHolder`2.Definition
val set : elements:seq<'T> -> Set<'T> (requires comparison)

Full name: Microsoft.FSharp.Core.ExtraTopLevelOperators.set
val x : ('Arg -> 'Result)
property FunHolder.Definition: 'Arg -> 'Result
val x : int
val x : string
Multiple items
val string : value:'T -> string

Full name: Microsoft.FSharp.Core.Operators.string

--------------------
type string = System.String

Full name: Microsoft.FSharp.Core.string
val twice<'a,'b> : ('a -> 'b)

Full name: Script.twice
val x : int

Full name: Script.x
Multiple items
val int : value:'T -> int (requires member op_Explicit)

Full name: Microsoft.FSharp.Core.Operators.int

--------------------
type int = int32

Full name: Microsoft.FSharp.Core.int

--------------------
type int<'Measure> = int

Full name: Microsoft.FSharp.Core.int<_>
val y : string

Full name: Script.y
val z : unit * unit

Full name: Script.z
type unit = Unit

Full name: Microsoft.FSharp.Core.unit
Raw view New version

More information

Link:http://fssnip.net/hs
Posted:6 years ago
Author:Nobuhisa
Tags: functions