Hacker News new | past | comments | ask | show | jobs | submit login

Expressions can be nested arbitrarily and infinitely — like in math. You can take “x * x” and “3 * x” and add them into “xx + 3x”. You can pass that to a function like “log(xx + 3x)”. You could then divide that, square root it, on and on. You can combine the expressions however you want.

Statements can also be combined, but in a separate way. You have control flow blocks, and inside of those you have one serial list of statements. Control flow blocks and statements can only go in other control flow blocks, and not in expressions.

If you’re coming from languages like C or Python, that might not seem like a huge deal. Why would you want “x = 5” or “while y < 10:” in an expression?

Languages that focus more on expressions have surprisingly simple ways of expressing some things, though.

In Rust, “if” statements are fully expressions, so you can assign them:

    let x = if y > 10 {
        let a = readLine().parse();
        let b = readLine().parse();
        a + b
    } else {
        y * 2
Another neat feature is that macros can return blocks, and you can still call those macros wherever you like. For example, in the standard library, there is a “try!” macro that checks if a value is successful. It expands basically into:

    if result is successful {
    } else {
        return result.error
The “return” there basically causes the error to short-circuit up the stack. In practice, that means that you can use “try!” to simply say “give me the successful value, and if there was an error, just send it up the stack.”

If you wanna get really fancy, languages like Haskell and Elm don’t have side effects, so things like “x = 5” don’t exist. There are only expressions. You can create values that represent doing something (kind of like Redux actions), and there are lots of tools for combining those action values. Because it’s all expressions, you can combine them arbitrarily. If you have a common case for how you combine your effects, you can just make a plain old function for it, because it’s all just expressions.

Guidelines | FAQ | Support | API | Security | Lists | Bookmarklet | Legal | Apply to YC | Contact