@@ -99,8 +99,8 @@ object Test extends App {
99
99
private class Exc (msg : String ) extends Exception (msg)
100
100
def _throw (msg : String ) with CanThrow : Nothing = throw new Exc (msg)
101
101
def _try [T ](op : CanThrow |=> T )(handler : String => T ): T = {
102
- val ct = new CanThrow ()
103
- try op with ct
102
+ instance of CanThrow
103
+ try op
104
104
catch {
105
105
case ex : Exception => handler(ex.getMessage)
106
106
}
@@ -185,7 +185,7 @@ object Test extends App {
185
185
186
186
enum NCtx { case Pos , Neg }
187
187
188
- instance NegExp [T ] with (e : Exp [T ]) of Exp [NCtx => T ] {
188
+ instance [T ] with (e : Exp [T ]) of Exp [NCtx => T ] {
189
189
import NCtx ._
190
190
def lit (i : Int ) = {
191
191
case Pos => e.lit(i)
@@ -202,9 +202,38 @@ object Test extends App {
202
202
println(tf1[NCtx => String ](NCtx .Pos ))
203
203
204
204
def pushNeg [T ](e : NCtx => T ): T = e(NCtx .Pos )
205
-
206
205
println(pushNeg(tf1[NCtx => String ]))
207
-
208
206
println(pushNeg(pushNeg(pushNeg(tf1))): String )
209
207
208
+ instance [T ] with (e : Mult [T ]) of Mult [NCtx => T ] {
209
+ import NCtx ._
210
+ def mul (l : NCtx => T , r : NCtx => T ): NCtx => T = {
211
+ case Pos => e.mul(l(Pos ), r(Pos ))
212
+ case Neg => e.mul(l(Pos ), r(Neg ))
213
+ }
214
+ }
215
+
216
+ println(pushNeg(tfm1[NCtx => String ]))
217
+ println(pushNeg(tfm2[NCtx => String ]))
218
+
219
+ import IExp ._
220
+
221
+ // Going from type class encoding to ADT encoding
222
+ instance initialize of Exp [IExp ] {
223
+ def lit (i : Int ): IExp = Lit (i)
224
+ def neg (t : IExp ): IExp = Neg (t)
225
+ def add (l : IExp , r : IExp ): IExp = Add (l, r)
226
+ }
227
+
228
+ // Going from ADT encoding to type class encoding
229
+ def finalize [T ](i : IExp ) with (e : Exp [T ]): T = i match {
230
+ case Lit (l) => e.lit(l)
231
+ case Neg (n) => e.neg(finalize[T ](n))
232
+ case Add (l, r) => e.add(finalize[T ](l), finalize[T ](r))
233
+ }
234
+
235
+ type Ring [T ] = Exp [T ] |=> Mult [T ] |=> T
236
+
237
+ def tfm1a [T ]: Ring [T ] = add(lit(7 ), neg(mul(lit(1 ), lit(2 ))))
238
+ def tfm2a [T ]: Ring [T ] = mul(lit(7 ), tf1)
210
239
}
0 commit comments