Saturday 12 September 2009

HLint

I found mention of HLint via this post. Installing it was as simple as the instructions provided. The binary ended up in $HOME/.cabal/bin which confused me for a few minutes.

A quick run over my code showed many improvements that I could make. For example. I don't make as much use of eta reduction as I could and HLint not only tells me this, but suggests a solution.


./randomText.hs:15:1: Warning: Eta reduce
Found

createTrainingSet s
= foldl' updateMap Map.empty (wordPairs (words s))

Why not

createTrainingSet = foldl' updateMap Map.empty . wordPairs . words


I also use far too many brackets in my code. That's a combination of not knowing the precedence rules and switching over from Clojure! Again, a warning is provided and the minimum brackets required shown.

HLint also finds common patterns in code and suggests rewriting them in terms of fold or map. For example when I was trying to write my own map:


./myfunctions.hs:11:1: Error: Use map
Found

mymap f [] = []
mymap f (x : xs) = f x : mymap f xs

Why not

mymap f xs = map f xs


And similarly for written my version of length:


./myfunctions.hs:3:1: Warning: Use foldl
Found

mylength [] count = count
mylength (x : xs) count = mylength xs (1 + count)

Why not

mylength xs count = foldl (\ count x -> 1 + count) count xs


I'll definitely be making use of this before I post any more Haskell code!