Useful alternative control structures?

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

    One of the control structures that isn't available in many languages is the case-in type structure. Similar to a switch type structure, it allows you to have a neatly formatted list of possible options, but matches the first one that's true (rather then the first one that matches the input). A LISP of such such (which does have it):

    (cond
       ((evenp a) a)        ;if a is even return a
       ((> a 7) (/ a 2))    ;else if a is bigger than 7 return a/2
       ((< a 5) (- a 1))    ;else if a is smaller than 5 return a-1
       (t 17))              ;else return 17
    

    Or, for those that would prefer a more C-like format

    cond 
        (a % 2 == 0): 
            a;     break;
        (a > 7):
            a / 2; break;
        (a < 5):
            a - 1; break;
        default:
            17;    break;
    

    It's basically a more accurate representation of the if/elseif/elseif/else construct than a switch is, and it can come in extremely handing in expressing that logic in a clean, readable way.

提交回复
热议问题