🔷

Power QueryのSplitter.SplitByTextLengths関数をF#に移植してみた

2024/09/20に公開

これを
https://learn.microsoft.com/ja-jp/powerquery-m/splitter-splittextbylengths

こう

let splitTextByLengths lengths =
    let rec split lengths text acc =
        match lengths, text with
        | [], _ -> List.rev acc
        | _ :: rest, "" -> split rest "" ("" :: acc)
        | len :: rest, _ ->
            let part = text[.. len - 1]
            let remaining = text[len..]
            split rest remaining (part :: acc)

    fun text -> split lengths text []

こんな感じ

let split = splitTextBylengths [2; 3]
split "AB123"  // ["AB"; "123"]
split "AB12"   // ["AB"; "12"]
split "AB1234" // ["AB"; "123"]
split "A"      // ["A"; ""]
split ""       // [""; ""]

本家のはlengthsに続いて省略可能なboolを指定することで、末尾からの分割になるけど今回は省略。
F#だと素直に別の関数として作ったほうがやりやすいかな?

Discussion