[Haskell] Real life examples
lennart at augustsson.net
Wed Nov 24 03:00:38 EST 2004
Tomasz Zielonka wrote:
> On Tue, Nov 23, 2004 at 08:50:45PM -0800, John Meacham wrote:
>>Atom.hs from ginsu..
>>This is perhaps the best example, and an incredibly useful piece of code
>>for anyone struggling with space problems out there.
>>data Atom = ... (abstract)
>>instance Ord Atom
>>instance Eq Atom
>>toAtom :: String -> Atom
>>fromAtom :: Atom -> String
>>internally, Atom has a global hash table of strings -> atoms, note that
>>externally, Atom is truly purely functional. toAtom and fromAtom
>>although using internal state inside are real functions. the same
>>argument always returns the same (externally visible) result. This is
>>because the actual integer chosen is hidden, there is no way to get at
>>it outside the module.
> Just a nitpick: will this code always yield the same results?
> map fromAtom $ sort $ map toAtom $ words "Just a nitpick"
This is one of the very few cases where I've used unsafePerformIO
(because I too have implemented something like Atom :). To make
this work properly you need to actually compare the strings for
Ord, but you can compare "pointers" for Eq. Doing that, you don't
break Haskell semantics (but proving it seems tricky).
More information about the Haskell