←back to thread

498 points azhenley | 1 comments | | HN request time: 0.001s | source
Show context
noduerme ◴[] No.45767922[source]
Why loops specifically? Why not conditionals?

A lot of code needs to assemble a result set based on if/then or switch statements. Maybe you could add those in each step of a chain of inline functions, but what if you need to skip some of that logic in certain cases? It's often much more readable to start off with a null result and put your (relatively functional) code inside if/then blocks to clearly show different logic for different cases.

replies(1): >>45768158 #
turtletontine ◴[] No.45768158[source]
There’s no mutating happening here, for example:

  if cond:
      X = “yes”
  else:
      X = “no”
X is only ever assigned once, it’s actually still purely functional. And in Rust or Lisp or other expression languages, you can do stuff like this:

  let X = if cond { “yes” } else { “no” };

That’s a lot nicer than a trinary operator!
replies(2): >>45768287 #>>45771399 #
nielsbot ◴[] No.45768287[source]
Swift does let you declare an immutable variable without assigning a value to it immediately. As long as you assign a value to that variable once and only once on every code path before the variable is read:

    let x: Int
    if cond {
        x = 1
    } else { 
        x = 2
    }

    // read x here
replies(2): >>45769510 #>>45776832 #
1. sambishop ◴[] No.45776832{3}[source]
that's oldschool swift. the new hotness would be

  let x = if cond { 1 } else { 2 }