Expression Versus Statement

前端 未结 21 2066
别那么骄傲
别那么骄傲 2020-11-22 11:54

I\'m asking with regards to c#, but I assume its the same in most other languages.

Does anyone have a good definition of expressions and statements

21条回答
  •  说谎
    说谎 (楼主)
    2020-11-22 12:24

    Some things about expression based languages:


    Most important: Everything returns an value


    There is no difference between curly brackets and braces for delimiting code blocks and expressions, since everything is an expression. This doesn't prevent lexical scoping though: A local variable could be defined for the expression in which its definition is contained and all statements contained within that, for example.


    In an expression based language, everything returns a value. This can be a bit strange at first -- What does (FOR i = 1 TO 10 DO (print i)) return?

    Some simple examples:

    • (1) returns 1
    • (1 + 1) returns 2
    • (1 == 1) returns TRUE
    • (1 == 2) returns FALSE
    • (IF 1 == 1 THEN 10 ELSE 5) returns 10
    • (IF 1 == 2 THEN 10 ELSE 5) returns 5

    A couple more complex examples:

    • Some things, such as some function calls, don't really have a meaningful value to return (Things that only produce side effects?). Calling OpenADoor(), FlushTheToilet() or TwiddleYourThumbs() will return some sort of mundane value, such as OK, Done, or Success.
    • When multiple unlinked expressions are evaluated within one larger expression, the value of the last thing evaluated in the large expression becomes the value of the large expression. To take the example of (FOR i = 1 TO 10 DO (print i)), the value of the for loop is "10", it causes the (print i) expression to be evaluated 10 times, each time returning i as a string. The final time through returns 10, our final answer

    It often requires a slight change of mindset to get the most out of an expression based language, since the fact that everything is an expression makes it possible to 'inline' a lot of things

    As a quick example:

     FOR i = 1 to (IF MyString == "Hello, World!" THEN 10 ELSE 5) DO
     (
        LotsOfCode
     )
    

    is a perfectly valid replacement for the non expression-based

    IF MyString == "Hello, World!" THEN TempVar = 10 ELSE TempVar = 5 
    FOR i = 1 TO TempVar DO
    (    
        LotsOfCode  
    )
    

    In some cases, the layout that expression-based code permits feels much more natural to me

    Of course, this can lead to madness. As part of a hobby project in an expression-based scripting language called MaxScript, I managed to come up with this monster line

    IF FindSectionStart "rigidifiers" != 0 THEN FOR i = 1 TO (local rigidifier_array = (FOR i = (local NodeStart = FindsectionStart "rigidifiers" + 1) TO (FindSectionEnd(NodeStart) - 1) collect full_array[i])).count DO
    (
        LotsOfCode
    )
    

提交回复
热议问题