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:

Starting With Chords

A lot of people play fiddle. Basically nobody starts by learning chords before learning melodies. But that's actually how I learned. I started with chords. One of the nice things about learning to play violin this way is that you can go busking even…

via Anna Wise's Blog Posts November 15, 2024

Stuffies

I have some stuffies and I just have a bunny. Bunny is a rabbit. Woof is a seal. My favorite stuffie is bun bun. I play with my stuffies. Sometimes I jump up with them and I roll them. I can just throw them in the air when I want to play bthululubp wi…

via Nora Wise's Blog Posts November 15, 2024

You Can Buy A Malaria Net

2024 election takes

via Thing of Things November 6, 2024

more     (via openring)