Skip to content

Instantly share code, notes, and snippets.

@gusty
Last active July 20, 2023 15:19
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gusty/b6fac370bff36a665d75 to your computer and use it in GitHub Desktop.
Save gusty/b6fac370bff36a665d75 to your computer and use it in GitHub Desktop.
Polyvariadic functions in F#
// Unfortunatelly it stopped working in F# 4.1 after this PR https://github.com/Microsoft/visualfsharp/pull/1650
// Will ask to revert it
type FoldArgs<'t> = FoldArgs of ('t -> 't -> 't)
let inline foldArgs f (x:'t) (y:'t) :'rest = (FoldArgs f $ Unchecked.defaultof<'rest>) x y
type FoldArgs<'t> with
static member inline ($) (FoldArgs f, _:'t-> 'rest) = fun (a:'t) -> f a >> foldArgs f
static member ($) (FoldArgs f, _:'t ) = f
let x:int = foldArgs (+) 2 3
let y:int = foldArgs (+) 2 3 4
let z:int = foldArgs (+) 2 3 4 5
let d:decimal = foldArgs (+) 2M 3M 4M
let e:string = foldArgs (+) "h" "e" "l" "l" "o"
let f:float = foldArgs (+) 2. 3. 4.
let mult3Numbers a b c = a * b * c
let res2 = mult3Numbers 3 (foldArgs (+) 3 4) (foldArgs (+) 2 2 3 3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment