Posts Tagged ‘prefix’

Arithmetic

Thursday, May 8th, 2008

Just when I was beginning to think that maybe Ruby’s slight edge in readability made up for its big loss in consistency, I needed to use rational numbers:

  • Ruby: Rational(3,5)
  • Lisp: 3/5

Languages like Ruby and C are basically infix for arithmetic, and prefix for everything else.  For a web app (like most apps, come to think of it), I pretty much never do anything more than the most trivial arithmetic.  And here, in the one place where I do need something as complex as fractions(!), Ruby forces me to use prefix notation — which even Lisp, the prefix-notation king, doesn’t require.  And not just prefix notation, but spelling out the name of the numeric type I want.

This seems just so deeply, thoroughly wrong.

Pseudo-English

Thursday, April 17th, 2008

So I came across a feature to implement whose description read “X% of the time, do Y”.  I thought for a second, and then wrote:

class Numeric
  def percent_of_the_time
    yield if rand(100) < self
  end
end

This works great: 15.percent_of_the_time {puts "hello, world"}.

(My unit testing friends are probably freaking out over monkey-patching core classes to be nondeterministic.  Good!)

Then I got to wondering: why can’t I do this in Lisp?  In Arc some things are callable which normally aren’t, but that seems a bit too much like magic to me, and I’m not sure it’s easily extensible to this case.

The problem with making something pseudo-English is that you need to put the noun first, and in Lisp the verb always comes first.

The solution is more obvious than I’d thought: use a library like curly-infix, and then just write a normal function.  Thus, in Lisp, it can be as simple as:

{15 percent-of-the-time (format t "hello, world")}

The only gotcha is that this looks suspiciously like a single-dispatch method call, but if you’re using CLOS generic functions, it’s not.