Code examples and exercises

This entry into QuickCheck2 begins with a nice 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 such optimizations?

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

What I need is not theory, best practice, or analysis tools, but actual examples, or better yet, exercises .

+3


source to share


1 answer


Try hlint, it gives you tips 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 to the "ladder": http://book.realworldhaskell.org/read/code-case-study-parsing-a-binary-data-format. html # x_JR



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

+1


source







All Articles