danbal
danbal

Reputation: 1531

Examples and exercises of code improvement

This intro to QuickCheck2 starts off with a beautiful example of code improvement.

Before

getList = find 5 where
     find 0 = return []
     find n = do
       ch <- getChar
       if ch `elem` ['a'..'e'] then do
             tl <- find (n-1)
             return (ch : tl) else
           find n

After

-- A thin monadic skin layer
getList :: IO [Char]
getList = fmap take5 getContents

-- The actual worker
take5 :: [Char] -> [Char]
take5 = take 5 . filter (`elem` ['a'..'e'])


Where can we find more examples of optimizations like this?

Where we have some code that works, but smells for some reason (hard to test, not reusable, etc.), and then we find a smart way to make it good enough.

What I'm after is not theory, best practises or tools of analysis, but actual examples or, even better, exercises.

Upvotes: 3

Views: 129

Answers (1)

rethab
rethab

Reputation: 8413

Try hlint, it gives you suggestions on how to improve your code: http://community.haskell.org/~ndm/hlint/

Since you are asking for specific examples, here's one from Real World Haskell on how to get ride of 'staircasing': http://book.realworldhaskell.org/read/code-case-study-parsing-a-binary-data-format.html#x_JR

And then, of course, the more you write actual code, the more you'll see how you can make it more concise.

Upvotes: 2

Related Questions