Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rewrite rules with newtype

Rewrite rules can help with your program optimization. And I wonder if they would work if I wrap my objects in newtype. As it's known, newtype doesn't bring performance penalties, it's a compile-time wrapper which is gone at runtime. So I wonder if rewrite rules would still be triggered with newtype. For example, there're a lot of rules for Data.Text (What is fusion in Haskell?).

GHC user guide warns about non-smartness of algorithm:

GHC currently uses a very simple, syntactic, matching algorithm for matching a rule LHS with an expression. It seeks a substitution which makes the LHS and expression syntactically equal modulo alpha conversion. The pattern (rule), but not the expression, is eta-expanded if necessary. (Eta-expanding the expression can lead to laziness bugs.) But not beta conversion (that’s called higher-order matching).

And now I'm operating with Identity Text (for some reasons). Would I still get those performance benefits? I'm not an expert in rewrite rules to perform benchmarks by myself and ensure in their results.

like image 972
Shersh Avatar asked Apr 09 '17 09:04

Shersh


1 Answers

Rewrite rules are applied to GHC’s intermediate language Core (and not to Haskell). By that time, newtype have mostly disappeared. For example, Identity x becomes x |> c where c is a coercion that casts x :: Text into something of type Identity Text.

These casts can cancel each other out, and then the rules can fire as usual. So you still should be able to get the benefits of the text rewrite rules, if everything falls into place.

Unfortunately, there are no hard guarantees, and without looking at the intermediate code (and known what to look for, e.g. if you know a certain place where fusion is supposed to happen) you cannot be sure that using Identity does not come at a cost here.

like image 154
Joachim Breitner Avatar answered Sep 27 '22 21:09

Joachim Breitner