Significant Whitespace In Expressions

January 8th, 2011
ideas, math, programming, tech
Order of operations can conflict with what an expression looks like it should mean. For example, the expression a * b+c looks like it means a*(b+c) but technically (and in most computer languages) means (a*b)+c. This seems analagous to the reasoning behind python using indentation instead of braces. The C code:
  if (x)
     if (y)
       z();
  else
     w();
looks like it should mean
  if (x) {
    if (y) {
      z();
    }
  }
  else {
    w();
  }
but actually means
  if (x) {
    if (y) {
       z();
    }
    else {
      w();
    }
  }
Python deals with this by treating the whitespace as significant, so:
  if x:
    if y:
      z()
    else:
      w()
and
  if x:
    if y:
       z()
  else:
    w()
both mean what they look like they should mean.

Some examples of how I would propose we do things instead:

  write                 to mean
  -----                 -------
  a+b                   a+b
  a + b*c               a+(b*c)
  a * b+c               a*(b+c)
  a+b * c+d             (a+b)*(c+d)
  a+b - c+d             (a+b)-(c+d)
  a+b  *  c+d - e+f     (a+b) * ((c+d) - (e+f))
  a  *  c + d + e       a*(c+d+e)
  a + b                 a+b, maybe yields warning
  a-b+c                 error
  a*b+c                 error
Algorithm:
for each number of spaces 0 on up:
  group any terms with that number of internal
  spaces by adding parens

Comment via: facebook

Recent posts on blogs I like:

Book Review: The Myth of Sex Addiction

I. David Ley’s The Myth of Sex Addiction is a stupid, wrong book saved only by the fact that the people it’s arguing with are stupider and wronger. II. “Sex addiction” is a proposed mental health condition, not recognized by the DSM or the ICD, where a pe…

via Thing of Things March 7, 2024

Your wedding doesn’t have to be that great

Your future happiness does not depend on how gorgeous this one day is. The post Your wedding doesn’t have to be that great appeared first on Otherwise.

via Otherwise March 4, 2024

When Nurses Lie to You

When the nurse comes to give you the flu shot, they say it won't hurt at all, right? And you trust them. Then they give you the shot, and it hurts! They lied to you. A lot of nurses lie to children about shots and blood draws. Part of it is they probabl…

via Lily Wise's Blog Posts February 28, 2024

more     (via openring)