Archive for December, 2008

Write Custom Spirit Iterators/Parsers

Tuesday, December 30th, 2008

The easiest way to write a Boost Spirit Parser is to define a functor_parser (boost/spirit/home/classic/utility/functor_parser.hpp).

To use it you have to define a functor(struct with a operator()):


struct function_functor
{
typedef nil_t result_t;

template
std::ptrdiff_t
operator() (ScannerT const& scan, result_t& result) const
{
// Return -1 if parsing was unsuccesful or number of characters parsed if successful.
}
};

result_t is the attribute type of the parser: int, float, etc. Default is nil_t. result will be passed to the action associated with the parser.

How to install Intel C Compiler (ICC) In Ubuntu 8.10

Tuesday, December 16th, 2008

To install icc in Ubuntu:

  1. Download icc from Intel website
  2. tar -zxvf the file.
  3. Run ‘install.sh’.
  4. Follow the installer instructions.
  5. When it is done add this line to your ~/.bashrc (or initialization script):
    source /opt/intel/Compiler/11.0/069/bin/iccvars.sh ia32
    Replace ia32 with your platform: (ia32, intel64, ia64)
  6. Log off and log in and that is it. You can test it with icc -v
  7. To use icc with a configure script use ./configure CC=icc

Ruby 1.9 C API Extension Guide

Tuesday, December 9th, 2008

I am writing a guide on the Ruby (SVN) C API. You can see it here: http://coaxialhost.com/tutorials/writing_ruby_extensions.html.

Expect more stuff to be added later.

Ruby Blocks 101

Tuesday, December 9th, 2008
  • Every function can accept a block.
  • Kernel.block_given? will tell you if a block was passed.
  • 
    def test
      a = 42
      yield(a) if block_given?
    end
    
  • To assign the block to an argument, you add an ampersand (&) in front of the last argument of your function. This will affect performance.
  • You can call the block inside the function using yield or Proc.call like this:
  • 
    def test(&block)
      a = 42
      yield(a) # or block.call(a,b)
    end
    
  • yield calls and passes the arguments to the block.
  • block.arity will tell you the number of arguments a block can accept
  • If you have a recursive function accepting a block, you can pass the block to it using ‘&’.
  • 
    def recursive_function(&block)
      # Do stuff
      recursive_function(&block)
      # pass to other functions accepting blocks
      10.times &block # will run block 10 times
    end
    
  • If you use the return keyword inside a block, it will return the value and exit the function binded to the block, which is the one that created it.
  • 
    def bl(&block)
      yield
    end
    
    def test
      bl { return }
      puts "Hello" # this will not be executed.
    end
    
  • You can use break to return a value inside a block and stop iterating.
  • 
    def bl(&block)
      (0..10).each &block
    end
    
    def test
      # This block will stop iterating at 5 and return true.
      bl { |x| (break true) if (x == 5); false }
    end