[Haskell-cafe] Reducing code for efficient ShowS
wren ng thornton
wren at freegeek.org
Fri Sep 5 15:32:12 EDT 2008
Sean Leather wrote:
> There's the obvious approach that's described in every tutorial, book, and
> research paper (for didactic purposes, of course).
>
>> ex1 = "(" ++ show n ++ " " ++ s ++ ")"
>
> It's pretty concise, but it's horribly inefficient due to the use of (++).
>
> Then, there's the ShowS approach.
>
>> ex2 = showChar '(' . shows n . showChar ' ' . showString s . showChar ')'
> $ ""
>
> This is more efficient, but now the code has bloated up a lot.
>
> Why can't I have my cake and eat it, too? I want to write with as little
> code as
> |ex1| (or less if possible), and I want it to be as efficient as |ex2|.
>
> I propose this example as an improvement.
>
>> ex3 = '(' .+. n .+. ' ' .+. s .$. ')'
Why not use the dlist library:
http://hackage.haskell.org/cgi-bin/hackage-scripts/package/dlist
With something like (untested code):
> xs +++ ys = shows xs `append` shows ys
> x .++ ys = showChar x `cons` shows ys
> xs ++. y = shows xs `snoc` showChar y
>
> ext3' = toList $ '(' .++ n +++ ' ' .++ s ++. ')'
--
Live well,
~wren
More information about the Haskell-Cafe
mailing list