• Posts
  • RSS
  • ◂◂RSS
  • Contact

  • Significant Whitespace In Expressions

    January 8th, 2011
    math, programming, ideas  [html]
    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:

    More on the Deutschlandtakt

    The Deutschlandtakt plans are out now. They cover investment through 2040, but even beforehand, there’s a plan for something like a national integrated timetable by 2030, with trains connecting the major cities every 30 minutes rather than hourly. But the…

    via Pedestrian Observations July 1, 2020

    How do cars fare in crash tests they're not specifically optimized for?

    Any time you have a benchmark that gets taken seriously, some people will start gaming the benchmark. Some famous examples in computing are the CPU benchmark specfp and video game benchmarks. With specfp, Sun managed to increase its score on 179.art (a su…

    via Posts on Dan Luu June 30, 2020

    Quick note on the name of this blog

    When I was 21 a friend introduced me to a volume of poems by the 14th-century Persian poet Hafiz, translated by Daniel Ladinsky. I loved them, and eventually named this blog for one of my favorite ones. At some point I read more and found that Ladinsky’s …

    via The whole sky June 21, 2020

    more     (via openring)


  • Posts
  • RSS
  • ◂◂RSS
  • Contact