1 Jun 2005 08:07
Simulating OO programming with type classes; writing a factory fu nction
<oleg <at> pobox.com>
2005-06-01 06:07:59 GMT
2005-06-01 06:07:59 GMT
Alistair Bayley wrote: > There's a small problem: how to write a factory function that returns values > of various subtypes. The makeSubType function below won't compile, obviously > because the returns types are different (they're not the same 'm'). Indeed, expressions in both branches of an `if' statement > if s == "SubBase1" > then SubBase1 3 > else SubBase2 (SubBase1 4) must be of the same type. If we had intersection types (I'm not complaining!), the compiler would have derived the intersection by itself. As things are now, we have to make the intersection manually: we have to abstract away irrelevant pieces. Expressions `SubBase1 3' and `SubBase2 (SubBase1 4)' have in common the fact that both have types that are instances of a Method class. So, we have to write that common piece of information explicitly. There are two ways of doing this, which can be called direct style and CPS style. In direct style, we do > data WM = forall m. Method m => WM m > makeSubType1 :: String -> WM > makeSubType1 s = > if s == "SubBase1" > then WM $ SubBase1 3 > else WM $ SubBase2 (SubBase1 4) >(Continue reading)

Peter
RSS Feed