Useful alternative control structures?

后端 未结 28 918
礼貌的吻别
礼貌的吻别 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:02

    I think I should mention CityScript (the scripting language of CityDesk) which has some really fancy looping constructs.

    From the help file:

    {$ forEach n var in (condition) sort-order $}
    ... text which appears for each item ....
    {$ between $}
    .. text which appears between each two items ....
    {$ odd $}
    .. text which appears for every other item, including the first ....
    {$ even $}
    .. text which appears for every other item, starting with the second ....
    {$ else $}
    .. text which appears if there are no items matching condition ....
    {$ before $}
    ..text which appears before the loop, only if there are items matching condition
    {$ after $}
    ..text which appears after the loop, only of there are items matching condition
    {$ next $}
    
    0 讨论(0)
  • 2021-01-30 03:02
    foo();
    
    while(condition)
    {
       bar();
       foo();
    }
    
    0 讨论(0)
  • 2021-01-30 03:02

    Loop with else:

    while (condition) {
      // ...
    }
    else {
      // the else runs if the loop didn't run
    }
    
    0 讨论(0)
  • 2021-01-30 03:03

    Also note that many control structures get a new meaning in monadic context, depending on the particular monad - look at mapM, filterM, whileM, sequence etc. in Haskell.

    0 讨论(0)
  • 2021-01-30 03:04

    if not:

    unless (condition) {
      // ...
    }
    

    while not:

    until (condition) {
      // ...
    }
    
    0 讨论(0)
  • 2021-01-30 03:04

    Something that replaces

    bool found = false;
    for (int i = 0; i < N; i++) {
      if (hasProperty(A[i])) {
        found = true;
        DoSomething(A[i]);
        break;
      }
    }
    if (!found) {
      ...
    }
    

    like

    for (int i = 0; i < N; i++) {
      if (hasProperty(A[i])) {
        DoSomething(A[i]);
        break;
      }
    } ifnotinterrupted {
      ...
    }
    

    I always feel that there must be a better way than introducing a flag just to execute something after the last (regular) execution of the loop body. One could check !(i < N), but i is out of scope after the loop.

    0 讨论(0)
提交回复
热议问题