From: Kristof Bastiaensen Date: 2006-07-27T00:15:09+09:00 Subject: Re: For performance, write it in C On Wed, 26 Jul 2006 17:47:13 +0900, Peter Hickman wrote: > Whenever the question of performance comes up with scripting languages > such as Ruby, Perl or Python there will be people whose response can be > summarised as "Write it in C". I am one such person. Some people take > offence at this and label us trolls or heretics of the true programming > language (take your pick). > > Hi, When reading your C code, I saw that there is a lot of code that is generated. I'd be interested to see how well the C program does if it can work for any size of the squares. In this case I think the problem is well suited for logic languages. I wrote a version in the functional logic language Curry, which does reasonably well. It will probably not be faster than the C version, but a lot faster than a program written in Ruby/Perl/Python. >If you really really want that performance boost then take the following > advice very seriously - "Write it in C". It can be a good idea to rewrite parts in C, but I would first check if the algorithms are good, so that it may not even be needed to write any C code. And perhaps there are libraries or tools that do the trick efficiently. I would keep writing C code as the last option. Regards, Kristof -------------------- start of latin.curry ---------------------------- -- upto is a nondeterministic function that evaluates to -- a number from 1 upto n upto 1 = 1 upto n | n > 1 = n ? upto (n-1) -- check if the lists r s have no element with the same value at the -- same position elems_diff r s = and $ zipWith (/=) r s -- extend takes a list of columns, and extends each column with a -- number for the next row. It checks the number agains the column and -- against the previous numbers in the row. extend :: [[Int]] -> Int -> [[Int]] extend cols n = addnum cols [] where addnum [] _ = [] addnum (col:cs) prev | x =:= upto n & (x `elem` prev) =:= False & (x `elem` col) =:= False = (x:col) : addnum cs (x:prev) where x free latin_square n = latin_square_ n where latin_square_ 0 = replicate n [] -- initalize columns to nil latin_square_ m | m > 0 = extend (latin_square_ (m-1)) n square2str s = unlines $ map format_col s where format_col col = unwords $ map show col main = mapIO_ (putStrLn . square2str) (findall (\s -> s =:= latin_square 5)) ------------------------- end latin.curry -----------------------------