[Haskell-cafe] How do you rewrite your code?

Max Bolingbroke batterseapower at hotmail.com
Wed Mar 3 13:52:43 EST 2010


Something I've been doing a lot lately is selective
defunctionalisation, transformation into continuation passing style,
and the combination of both things (CPS followed by defunctionalising
the continuations). This is probably because I'm playing around with
lambda calculus evaluators a lot though :-) (see Olivier Danvy's
homepage for more: http://www.cs.au.dk/~danvy/)

Cheers,
Max

On 2 March 2010 19:20, Sean Leather <leather at cs.uu.nl> wrote:
> There are numerous threads on the Haskell Café involving rewriting,
> refactoring, refining, and in general improving code (for some definition of
> improve). I am interested in seeing examples of how Haskell code can be
> rewritten to make it better. Some general examples are:
>
> Eta-reduce
> Make more pointfree
> Introduce monadic operators or do-notation
>
> e.g. for Maybe, lists, State
>
> Eliminate monadic operators or do-notation
> Generalize types
>
> e.g. change map to fmap, (++) to mappend
>
> Use instances of Functor, Applicative, Alternative, Category, Arrow, Monoid,
> Traversable, etc.
> Use library functions from Data.List, Data.Map, Data.Set, etc.
> Use some form of generic programming (e.g. SYB, Uniplate, EMGM, Alloy)
> Use other libraries not included in the Platform
>
> My question is simple:
>
>    How do you rewrite your code to improve it?
>
> You can answer this in any way you like, but I think the most useful answer
> is to show a reasonably small, concrete example of what your code looked
> like before and after. Also, please describe how you think the rewrite
> improves such code.
>
> Is it better style? More useful? More efficient?
> Are the types (before and after) the same?
> Are the semantics the same?
> How did you prove or test equivalence? (e.g. Can you use equational
> reasoning to confirm the rewrite is valid? Did you use QuickCheck?)
>
> Here is an example that I find myself doing occasionally.
>
> For all x, f:
>
> x >>= return . f
> -->
> fmap f x
> or
> f <$> x -- requires importing Control.Applicative
>
> I think the right-hand side (RHS) is more concise and simpler. The types
> here do change: the type constructor has a Monad constraint in the left-hand
> side and a Functor constraint in the RHS. Types that are Monad instances are
> generally also Functor instances, so this is often possible. I'm convinced
> the semantics are preserved, though I haven't proven it.
>
> What's an example of a rewrite that you've encountered?
>
> Thanks,
> Sean
>
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe
>
>


More information about the Haskell-Cafe mailing list