[Haskell-beginners] pattern match vs. pure function

Brent Yorgey byorgey at seas.upenn.edu
Wed Oct 20 09:14:04 EDT 2010


On Wed, Oct 20, 2010 at 01:23:49AM +0200, Bastian Erdnüß wrote:
> Suppose I would want to write a function rmap that acts like
> 
>   rmap [f,g,h] x == [f x, g x, h x]
> 
> Do I gain any advantage or disadvantage (beside readability) from using
> 
>   rmap = flip $ map . flip id
> 
> over
> 
>   rmap []     _ = []
>   rmap (f:fs) x = f x : rmap fs x
> 
> ?

By the way, I would write rmap as

  rmap fs x = map ($x) fs

which is (in my opinion) many times more readable than flip $ map
. flip id.  In this case there's no particular advantage to a
points-free definition.  But using an existing recursive combinator
(map) is a big win over writing out the recursion explicitly.

> I could imagine Haskell can optimize the first version better since
> it refers to the built in map function.  But beside that, does
> Haskell struggle with the combinatory stuff in the first version?
> Or does it get optimized away?  And how "expensive" are pattern
> matches on the other side, anyway?

It's a fair question, and Daniel has already given a detailed answer.
But honestly, I don't think this is the sort of thing you should
really be worrying about.  Write your programs in the most natural,
elegant way you can think of, and trust that the compiler will try
very hard to turn it into efficient code.  If it later turns out to be
too slow and profiling seems to indicate there's room for improvement,
THEN you can start worrying about this sort of thing.

-Brent


More information about the Beginners mailing list