[Haskell-cafe] Newbie Haskell optimization question
Slavomir Kaslev
slavomir.kaslev at gmail.com
Mon Nov 20 17:16:44 EST 2006
Hello,
I am new to Haskell and I am having fun with it writing L-system
generator. I was very pleased with concise syntax. It's an order of
magnitude better than any C++, Lisp, etc program I've ever written or
read.
Doing algorithmic optimizations on my generator I ended up with 4
different versions (you can see the other 3 in the file attached). The
most optimal of them is:
import qualified Data.Map
type LSystemElement = (Char, [Int])
type LSystem = [LSystemElement]
type LSystemRules = Data.Map.Map Char (LSystemElement -> LSystem)
generate'' :: LSystemRules -> LSystem -> Int -> LSystem
generate'' rules axiom steps =
concatMap (iterate f axiom !!) (ind !! steps)
where
ind = [0] : [g x | x <- ind]
where
g [] = []
g [x] = [x, x + 1]
g xs = xs ++ g (drop (length xs `div` 2) xs)
f = concatMap $ \elem -> Data.Map.findWithDefault (\x -> [x])
(fst elem) rules elem
-- Tests
a (_, [x, y]) | y <= 2 = [('A', [x + 2, y + 2])]
| otherwise = [('B', [2]), ('A', [x - 1, y - 1])]
b (_, [x]) | x <= 2 = [('C', [])]
| otherwise = [('B', [x - 1])]
rules = Data.Map.fromList [('A', a), ('B', b)]
axiom = [('A', [2, 2])]
Now I am thinking of doing some language level optimizations. Can you
give me any (random) directions? Any style recommendations are welcome
as well.
Cheers.
--
Slavomir Kaslev
-------------- next part --------------
A non-text attachment was scrubbed...
Name: lsys.hs
Type: application/octet-stream
Size: 1999 bytes
Desc: not available
Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20061121/22a27537/lsys.obj
More information about the Haskell-Cafe
mailing list