Skip to content

Instantly share code, notes, and snippets.

@Hugoberry
Created March 23, 2018 11:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Hugoberry/3f0bdefb2322f5b58d3063fe56bc8107 to your computer and use it in GitHub Desktop.
Save Hugoberry/3f0bdefb2322f5b58d3063fe56bc8107 to your computer and use it in GitHub Desktop.
[Power Query] function curry with up to N levels and maintaining function signature types
Function.CurryN = (function as function, optional N) =>
let
functionType = Value.Type(function),
parameters = Type.FunctionParameters(functionType),
minCount = Type.FunctionRequiredParameters(functionType),
arity = Record.FieldCount(parameters),
pos = if N = null then arity else N,
Apply = (args) =>
let
idx = List.Count(args)
in if (idx >= pos) and (pos < minCount)
then List.Accumulate(args,function,Function.PartialApply)
else if idx >= pos
then Function.Invoke(function, args)
else Function.From(
Type.ForFunction(
[ Parameters = Record.SelectFields(parameters,Record.FieldNames(parameters){idx}),
ReturnType = Type.FunctionReturn(functionType)], 1),
(list) => @Apply(args & {list{0}}))
in
Apply({})
= Function.CurryN(Text.Contains)("Abc")("a")(Comparer.OrdinalIgnoreCase)
= Function.CurryN(Text.Contains,2)("Abc")("a")
= Function.CurryN(Text.Contains,1)("Abc")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment