Tagged CTFE

One of the most distinctive features of Common Lisp and Lisp in general, are its code-generation and code-manipulation capabilities.

Probably the best example is the LOOP macro - a Swiss Army knife of iteration that can do pretty much anything. The following snippet iterates a list of random numbers collecting some statistics of its contents and does that while being very concise and readable:

(let ((random (loop with max = 500
                    for i from 0 to max
                    collect (random max))))
  (loop for i in random
          counting (evenp i) into evens
          counting (oddp i) into odds
          summing i into total
          maximizing i into max
          minimizing i into min
        finally (format t "Stats: ~A"
                          (list min max total evens odds))))
Stats: (0 499 120808 261 240)

Continue reading

There's an increasing interest with the D programming language amongst my readers so I figured I'll post a bunch of short posts about D and see what happens.

Anyway, here's a classic example showing Ruby's capabilities taken from Seven Languages in Seven Weeks:

class Roman
  def self.method_missing name, *args
    roman = name.to_s
    roman.gsub!("IV", "IIII")
    roman.gsub!("IX", "VIIII")
    roman.gsub!("XL", "XXXX")
    roman.gsub!("XC", "LXXXX")

    (roman.count("I") +
     roman.count("V") * 5 +
     roman.count("X") * 10 +
     roman.count("L") * 50 +
     roman.count("C") * 100)
  end
end

puts Roman.X
puts Roman.XC
puts Roman.XII

Continue reading