6.11. Rewrite rules

The programmer can specify rewrite rules as part of the source program (in a pragma). GHC applies these rewrite rules wherever it can.

Here is an example:
  {-# RULES
        "map/map"       forall f g xs. map f (map g xs) = map (f.g) xs

6.11.1. Syntax

From a syntactic point of view:

6.11.2. Semantics

From a semantic point of view:

6.11.3. List fusion

The RULES mechanism is used to implement fusion (deforestation) of common list functions. If a "good consumer" consumes an intermediate list constructed by a "good producer", the intermediate list should be eliminated entirely.

The following are good producers:

The following are good consumers:

So, for example, the following should generate no intermediate lists:
array (1,10) [(i,i*i) | i <- map (+ 1) [0..9]]

This list could readily be extended; if there are Prelude functions that you use a lot which are not included, please tell us.

If you want to write your own good consumers or producers, look at the Prelude definitions of the above functions to see how to do so.

6.11.4. Specialisation

Rewrite rules can be used to get the same effect as a feature present in earlier version of GHC:
  {-# SPECIALIZE fromIntegral :: Int8 -> Int16 = int8ToInt16 #-}
This told GHC to use int8ToInt16 instead of fromIntegral whenever the latter was called with type Int8 -> Int16. That is, rather than specialising the original definition of fromIntegral the programmer is promising that it is safe to use int8ToInt16 instead.

This feature is no longer in GHC. But rewrite rules let you do the same thing:
  "fromIntegral/Int8/Int16" fromIntegral = int8ToInt16
This slightly odd-looking rule instructs GHC to replace fromIntegral by int8ToInt16 whenever the types match. Speaking more operationally, GHC adds the type and dictionary applications to get the typed rule
forall (d1::Integral Int8) (d2::Num Int16) .
        fromIntegral Int8 Int16 d1 d2 = int8ToInt16
What is more, this rule does not need to be in the same file as fromIntegral, unlike the SPECIALISE pragmas which currently do (so that they have an original definition available to specialise).

6.11.5. Controlling what's going on