[Haskell-cafe] function unique

Jonathan Cast jcast at ou.edu
Thu Jul 12 17:53:38 EDT 2007


On Thursday 12 July 2007, Dan Weston wrote:
> While we're at it, the second pattern match is superfluous. Once you
> take out nonempty lists from the list type, the only thing left is an
> empty one!
>
> unique :: Eq a => [a] -> [a]
> unique (x:xs) = x : (unique . filter (/= x) $ xs)
> unique _      = []
>
> One question left: would the second definition be more efficient if
> written:
>
> unique e = e
>
> Inquiring minds want to know...

No.  Of course not.  Before making wild guesses about how GHC is implementing 
your code, read (and understand[1]) the STG paper:

http://research.microsoft.com/copyright/accept.asp?path=/users/simonpj/papers/spineless-tagless-gmachine.ps.gz&pub=34

And then as many as you can of the other papers available here.

http://research.microsoft.com/~simonpj/Papers/papers.html

To answer your question: [] is treated like a variable, except it's a variable 
whose behavior is statically known, so the compiler can do more with it.  In 
fact, all of your versions given are equivalent in GHC, but only because 
you're taking advantage of more and more of the heroic work GHC does to 
convert your later versions into your earlier ones.

Jonathan Cast
http://sourceforge.net/projects/fid-core
http://sourceforge.net/projects/fid-emacs

[1] Understanding the STG paper is not a requirement to using Haskell, just to 
making wild (incorrect) guesses about how the compiler's going to treat your 
code.  But, of course, making wild (incorrect) guesses about how the 
compiler's going to treat your code is not a requirement to using Haskell.


More information about the Haskell-Cafe mailing list