Forum Discussion
The 'right' way to bring a custom function requiring arguments 'inline'
- 1 year ago
p45cal , regarding "in-line" function definition and call: consider Function.Invoke as an alternative. Example:
( ) => 5 // this is our function ( ( ) => 5 )( ) // this is how you call it now Function.Invoke( ( ) => 5, { } ) // alternative way to call our functionI am not aware of any other alternatives. And there is nothing wrong with your current approach. But the fact that you apply it to solve that particular problem (the one with different "_" conflicting each other) does not look like a ... reasonable one in that particular case. The problem is solved by different identifiers, not by "in-line function call".
The each keyword is a syntax replacement for "(_)=>". Also, when accessing a field without an identifier, it will default to referencing the variable named "_" in the environment (or call it an identifier).
So, in fact, it is like this:
Table.AddColumn(ChangedType, "ListMonths",
(_) => List.Generate(
() => _[Start Date],
(_) => _ <= _[End Date],
(_) => Date.AddMonths(_, 1)
)
)
The "startdate" field cannot find a variable named "_" in the function (() => _[Start Date]), so it will jump out of the List.Generate function, so it can access the row information in the original table normally. However, "enddate" cannot. Since there is a variable named "_" in the function definition ((_) => _ <= _[End Date]), so it will use the "_" here. It will not jump out of the List.Generate function.
Similar problems also exist in other programming languages, which usually follow the "proximity principle", that is, looking for variables in the current environment (or scope), and if not found, go to the outer layer until the root environment.
AlienSx has already given the answer, but it should be noted that [startdate] is not ambiguous, so it can be modified or not, but [enddate] must be modified.
Here is another way to modify it:
let
Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("JcfBDQAgCASwXe5NwglidBbC/msosb9mgkO51GgOgb9EZ6IkMbby/AroSusEqi4=", BinaryEncoding.Base64), Compression.Deflate)),{"Start Date","End Date"}),
ChangedType = Table.TransformColumnTypes(Source,{{"Start Date", type date}, {"End Date", type date}},"en-GB"),
Custom1 = Table.AddColumn(ChangedType, "ListMonths", each
List.Generate(
()=>[Start Date],
// Only modify this line
(x) => x <= [End Date],
each Date.AddMonths(_, 1))
)
in
Custom1