Useful alternative control structures?

后端 未结 28 1690
礼貌的吻别
礼貌的吻别 2021-01-30 02:20

Sometimes when I am programming, I find that some particular control structure would be very useful to me, but is not directly available in my programming language. I think my

28条回答
  •  不知归路
    2021-01-30 03:06

    Most languages have built-in functions to cover the common cases, but "fencepost" loops are always a chore: loops where you want to do something on each iteration and also do something else between iterations. For example, joining strings with a separator:

    string result = "";
    for (int i = 0; i < items.Count; i++) {
        result += items[i];
        if (i < items.Count - 1) result += ", "; // This is gross.
        // What if I can't access items by index?
        // I have off-by-one errors *every* time I do this.
    }
    

    I know folds can cover this case, but sometimes you want something imperative. It would be cool if you could do:

    string result = "";
    foreach (var item in items) {
        result += item;
    } between {
        result += ", ";
    }
    

提交回复
热议问题