Algorithm for joining e.g. an array of strings

后端 未结 16 1880
陌清茗
陌清茗 2021-01-01 21:40

I have wondered for some time, what a nice, clean solution for joining an array of strings might look like. Example: I have [\"Alpha\", \"Beta\", \"Gamma\"] and want to join

16条回答
  •  南笙
    南笙 (楼主)
    2021-01-01 22:17

    For pure elegance, a typical recursive functional-language solution is quite nice. This isn't in an actual language syntax but you get the idea (it's also hardcoded to use comma separator):

    join([]) = ""

    join([x]) = "x"

    join([x, rest]) = "x," + join(rest)

    In reality you would write this in a more generic way, to reuse the same algorithm but abstract away the data type (doesn't have to be strings) and the operation (doesn't have to be concatenation with a comma in the middle). Then it usually gets called 'reduce', and many functional languages have this built in, e.g. multiplying all numbers in a list, in Lisp:

    (reduce #'* '(1 2 3 4 5)) => 120

提交回复
热议问题