C++ and the compile time faculty

Freitag, 1. Januar 2010

I hate C++ fanboys. "Look C++ is the most p0werful and shiny language ev4r. You can't do that with any other language." followed by a copy of the faculty example from FQA or Wikipedia:

#include <iostream>

using namespace std;

template<int n> struct fac {
        static const int value = n*fac<n-1>::value;
};

template<> struct fac<1> {
        static const int value = 1;
};

int main() {
        cout << fac<5>::value << endl;
        return 0;
}


C++ dissolves the template to a simple multiplication (if -ftemplate-depth >= 4) and *woohoo replaces the multiplication with the result at compile time. There are many languages (and language features) out there with this capability, p.ex. Lisp Macros, Scheme, MetaOcaml or Template Haskell:

Fac.hs:
module Fac where

fac n = product [1..n]


Main.hs:
{-# LANGUAGE TemplateHaskell #-}

module Main where

import Fac
import Language.Haskell.TH.Syntax

main = print $(lift $ fac (5 :: Int))


120 at compile time:
>ghc -ddump-simpl Main.hs | grep print | grep 120
Main.main = print_rSB (GHC.Integer.smallInteger 120)


Trackbacks


Trackback-URL für diesen Eintrag
    Keine Trackbacks

Kommentare


    Noch keine Kommentare

Kommentar schreiben


Um maschinelle und automatische Übertragung von Spamkommentaren zu verhindern, bitte die Zeichenfolge im dargestellten Bild in der Eingabemaske eintragen. Nur wenn die Zeichenfolge richtig eingegeben wurde, kann der Kommentar angenommen werden. Bitte beachten Sie, dass Ihr Browser Cookies unterstützen muss, um dieses Verfahren anzuwenden.
CAPTCHA

  Kommentare werden erst nach redaktioneller Prüfung freigeschaltet!