[Haskell-beginners] pattern match vs. pure function

Patrick LeBoutillier patrick.leboutillier at gmail.com
Wed Oct 20 10:04:41 EDT 2010


Hi,

On Wed, Oct 20, 2010 at 9:14 AM, Brent Yorgey <byorgey at seas.upenn.edu> wrote:
> 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
>>

A newbie question about this. I can figure out the type of "flip ($)"
and I can work it
from ghci:

  Prelude> :t flip
  flip :: (a -> b -> c) -> b -> a -> c
  Prelude> :t ($)
  ($) :: (a -> b) -> a -> b
  Prelude> :t flip ($)
  flip ($) :: b -> (b -> b1) -> b1

but I cannot understand how "flip id" is equivalent:

  Prelude> :t flip
  flip :: (a -> b -> c) -> b -> a -> c
  Prelude> :t id
  id :: a -> a
  Prelude> :t flip id
  flip id :: b -> (b -> c) -> c

How does one get the type of "flip id" by applying "flip" to "id"?


Thanks,

Patrick


>> 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
> _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://www.haskell.org/mailman/listinfo/beginners
>



-- 
=====================
Patrick LeBoutillier
Rosemère, Québec, Canada


More information about the Beginners mailing list