| 113 | | == TODO == |
| 114 | | |
| 115 | | == Overloading Pattern Matching on Lists == |
| 116 | | ... |
| | 113 | == TODO: Overloading Pattern Matching on Lists == |
| | 114 | |
| | 115 | One way to overload list patterns is to replace the {{{FromList}}} class from |
| | 116 | the previous section with the {{{OverloadedLists}}} class defined as follows: |
| | 117 | |
| | 118 | {{{ |
| | 119 | class OverloadedLists l where |
| | 120 | type Item l |
| | 121 | fromList :: [Item l] -> l |
| | 122 | toList :: l -> [Item l] |
| | 123 | |
| | 124 | fromListN :: Int -> [Item l] -> l |
| | 125 | fromListN _ = fromList |
| | 126 | }}} |
| | 127 | |
| | 128 | This class allows us to view the structure {{{l}}} as a list. Now, the |
| | 129 | {{{toList}}} can be used to overload the list notation in patters. |
| | 130 | For example, When the {{{OverloadedLists}}} extension is turned on, the |
| | 131 | definitions |
| | 132 | |
| | 133 | {{{ |
| | 134 | f [] = ... |
| | 135 | g [x,y,z] = ... |
| | 136 | }}} |
| | 137 | |
| | 138 | will be treated as |
| | 139 | |
| | 140 | {{{ |
| | 141 | f (toList -> []) = ... |
| | 142 | g (toList -> [x,y,z]) = ... |
| | 143 | }}} |
| | 144 | |
| | 145 | Here, just like for expression, we propose to overload list patterns that use |
| | 146 | square brackets. The {{{:}}} infix operator will remain list specific both in |
| | 147 | expressions and patterns. In other words, {{{:}}} is not overloaded. |
| | 148 | |
| | 149 | The instances of the {{{OverloadedLists}}} class should satisfy the following |
| | 150 | property: |
| | 151 | |
| | 152 | {{{ |
| | 153 | fromList . toList = id |
| | 154 | }}} |
| | 155 | |
| | 156 | The example {{{FromList}}} instances from the previous section can be extended |
| | 157 | into the {{{OverloadedLists}}} instances as follows: |
| | 158 | |
| | 159 | {{{ |
| | 160 | instance OverloadedLists [a] where |
| | 161 | type Item [a] = a |
| | 162 | fromList = id |
| | 163 | toList = id |
| | 164 | |
| | 165 | instance (Ord a) => OverloadedLists (Set a) where |
| | 166 | type Item (Set a) = a |
| | 167 | fromList = Set.fromList |
| | 168 | toList = Set.toList |
| | 169 | |
| | 170 | instance (Ord k) => OverloadedLists (Map k v) where |
| | 171 | type Item (Map k v) = (k,v) |
| | 172 | fromList = Map.fromList |
| | 173 | toList = Map.toList |
| | 174 | |
| | 175 | instance OverloadedLists (IntMap v) where |
| | 176 | type Item (IntMap v) = (Int,v) |
| | 177 | fromList = IntMap.fromList |
| | 178 | toList = IntMap.toList |
| | 179 | |
| | 180 | instance OverloadedLists Text where |
| | 181 | type Item Text = Char |
| | 182 | fromList = Text.pack |
| | 183 | toList = Text.unpack |
| | 184 | |
| | 185 | instance OverloadedLists (Vector a) where |
| | 186 | type Item (Vector a) = a |
| | 187 | fromList = Vector.fromList |
| | 188 | fromListN = Vector.fromListN |
| | 189 | toList = Vector.toList |
| | 190 | }}} |
| | 191 | |
| | 192 | == Further Improvements == |