| 43 | == Simple pattern synonyms == |
| 44 | The simplest form of pattern synonyms is the one from the examples above. The grammar rule is simply: |
| 45 | |
| 46 | `pattern` ''conid'' ''varid,,1,,'' ... ''varid,,n,,'' `=` ''patexp'' |
| 47 | |
| 48 | where ''patexp'' is simply the intersection of the grammars for patterns and expression, i.e., those terms that are valid both as a pattern and as an expressions. |
| 49 | Each of the variables on the left hand side must occur exactly one on the right hand side, and these are the only variables that can be mention on the right hand side. The semantics is simply given by expansions of the synonym. |
| 50 | Pattern synonyms are not allowed to be recursive. Cf. type synonyms. |
| 51 | |
| 52 | Pattern synonyms can be exported and imported by mentioning the ''conid'' in the export/import list. Note that this suffers from the same constructor vs type confusion that already exists in `hiding` list, i.e., given the mention of a ''conid'' you cannot tell if it refers to a constructor or a type. |
| 53 | |
| 54 | == Pattern only synonyms == |
| 55 | The simple patterns synonyms are restricted to having a right hand side that is also a valid expression. |
| 56 | The pattern only synonyms can have any pattern on the right hand side, but may only be used in patterns. |
| 57 | |
| 58 | `pattern` ''conid'' ''varid,,1,,'' ... ''varid,,n,,'' `~` ''pat'' |
| 59 | |
| 60 | Note the use of `~` instead of `=` as the equality symbol. This serves as a syntactic cue that this is a pattern only synonym. |
| 61 | Again, each of the variables on the left hand side must be mentioned exactly once of the right hand side, but the right hand side can mention other variables as well. These variables will not be bound by using the pattern synonyms. |
| 62 | |
| 63 | Examples: |
| 64 | {{{ |
| 65 | pattern ThirdElem x ~ _:_:x:_ |
| 66 | pattern LazySecond a b ~ (a, ~b) |
| 67 | |
| 68 | third (ThirdElem a) = a |
| 69 | third _ = error "No third" |
| 70 | fcn :: (Int, (Int, Int)) |
| 71 | fcn (LazySecond x (y, z)) = if x == 0 then 0 else y+z |
| 72 | }}} |
| 73 | And their expansions |
| 74 | {{{ |
| 75 | third (_:_:a:_) = a |
| 76 | third _ = error "No third" |
| 77 | fcn :: (Int, (Int, Int)) |
| 78 | fcn (x ~(y, z)) = if x == 0 then 0 else y+z |
| 79 | }}} |
| 80 | |
| 81 | |
| 82 | == Bidirectional synonyms == |