lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


> Though far less fun, this all makes me think at an opposite contest, namely one judging the clearest implementation of software things difficult to express clearly.

I like this idea, although "clearest" can be too in the eye of the beholder. Which implementation is the clearest?

function sqrt(x)
  local function good(guess) return math.abs((guess^2) - x) < 1e-5 and guess end
  local function better(guess) return (guess + x / guess) / 2 end
  local function try(guess) return good(guess) or try(better(guess)) end
  return try(10)
end

or

function sqrt(x)
  local guess = 10
  while math.abs(guess^2 - x) >= 1e-5 do
    guess = (guess + x / guess) / 2
  end
  return guess
end

One is clearly shorter, although I like "try(guess) return good(guess) or try(better(guess))", which succinctly describes the algorithm. One can come up with a shorter version:

function sqrt(x)
  local function try(guess) return math.abs((guess^2) - x) < 1e-5 and guess
    or try((guess + x / guess) / 2) end
  return try(10)
end

but, I'm not sure if it's any more clear than the original, more verbose, version.

Paul

On Mon, Nov 12, 2012 at 1:53 PM, spir <denis.spir@gmail.com> wrote:
On 2012-11-12 3:56 PM, "Marc Balmer" <marc@msys.ch> wrote:

[obfuscated code]

Though far less fun, this all makes me think at an opposite contest, namely one judging the clearest implementation of software things difficult to express clearly.

Denis