M 中的范围函数?

Range function in M?

是否可以在 M 中创建数值范围?例如:

let
    x = range(1,10) // {1,2,3,4,5,6,7,8,9,10}, from 1 to 10, increment by 1
    x = range(1,10,2) // {1,3,5,7,9}, from 1 to 10, increment by 2

对于简单的场景,a..b 可能比较合适。一些例子:

let
    firstList = {1..10}, // {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
    secondList = {1, 5, 12, 14..17, 18..20}, // {1, 5, 12, 14, 15, 16, 17, 18, 19, 20}
    thirdList = {Character.ToNumber("a")..100, 110..112}, // {97, 98, 99, 100, 110, 111, 112}
    fourthList = {95..(10 * 10)} // {95, 96, 97, 98, 99, 100}
in
    fourthList

否则,也许可以尝试内部使用 List.Generate:

的自定义函数
let
    range = (inclusiveStart as number, inclusiveEnd as number, optional step as number) as list => 
        let
            interval = if step = null then 1 else step,
            conditionFunc = 
                if (interval > 0) then each _ <= inclusiveEnd
                else if (interval < 0) then each _ >= inclusiveEnd
                else each false,
            generated = List.Generate(() => inclusiveStart, conditionFunc, each _ + interval)
        in generated,
    firstList = range(1, 10), // {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
    secondList = range(1, 10, 2), // {1, 3, 5, 7, 9}
    thirdList = range(1, 10 , -1), // {} due to the combination of negative "step", but "inclusiveEnd" > "inclusiveStart"
    fourthList = range(10, 1, 0), // {} current behaviour is to return an empty list if 0 is passed as "step" argument.
    fifthList = range(10, 1, -1), // {10, 9, 8, 7, 6, 5, 4, 3, 2, 1}
    sixthList = range(10, 1, 1) // {} due to the combination of positive "step", but "inclusiveEnd" < "inclusiveStart"
in
    sixthList

上面的range函数应该能够生成升序和降序序列(参见代码示例)。


或者,您可以创建一个在内部使用 List.Numbers 的自定义函数,方法是首先计算 count 参数需要的值。但我选择了 List.Generate.