| 1 |
= ObjectOrientedProgramming |
| 2 |
|
| 3 |
<<StandardML#,Standard ML>> does not have explicit support for |
| 4 |
object-oriented programming. Here are some papers that show how to |
| 5 |
express certain object-oriented concepts in SML. |
| 6 |
|
| 7 |
* <<References#Berthomieu00,OO Programming styles in ML>> |
| 8 |
|
| 9 |
* <<References#ThorupTofte94,Object-oriented programming and Standard ML>> |
| 10 |
|
| 11 |
* <<References#LarsenNiss04,mGTK: An SML binding of Gtk+>> |
| 12 |
|
| 13 |
* <<References#FluetPucella06,Phantom Types and Subtyping>> |
| 14 |
|
| 15 |
The question of OO programming in SML comes up every now and then. |
| 16 |
The following discusses a simple object-oriented (OO) programming |
| 17 |
technique in Standard ML. The reader is assumed to be able to read |
| 18 |
Java and SML code. |
| 19 |
|
| 20 |
|
| 21 |
== Motivation |
| 22 |
|
| 23 |
SML doesn't provide subtyping, but it does provide parametric |
| 24 |
polymorphism, which can be used to encode some forms of subtyping. |
| 25 |
Most articles on OO programming in SML concentrate on such encoding |
| 26 |
techniques. While those techniques are interesting -- and it is |
| 27 |
recommended to read such articles -- and sometimes useful, it seems |
| 28 |
that basically all OO gurus agree that (deep) subtyping (or |
| 29 |
inheritance) hierarchies aren't as practical as they were thought to |
| 30 |
be in the early OO days. "Good", flexible, "OO" designs tend to have |
| 31 |
a flat structure |
| 32 |
|
| 33 |
---- |
| 34 |
Interface |
| 35 |
^ |
| 36 |
| |
| 37 |
- - -+-------+-------+- - - |
| 38 |
| | | |
| 39 |
ImplA ImplB ImplC |
| 40 |
---- |
| 41 |
|
| 42 |
|
| 43 |
and deep inheritance hierarchies |
| 44 |
|
| 45 |
---- |
| 46 |
ClassA |
| 47 |
^ |
| 48 |
| |
| 49 |
ClassB |
| 50 |
^ |
| 51 |
| |
| 52 |
ClassC |
| 53 |
^ |
| 54 |
| |
| 55 |
---- |
| 56 |
|
| 57 |
tend to be signs of design mistakes. There are good underlying |
| 58 |
reasons for this, but a thorough discussion is not in the scope of |
| 59 |
this article. However, the point is that perhaps the encoding of |
| 60 |
subtyping is not as important as one might believe. In the following |
| 61 |
we ignore subtyping and rather concentrate on a very simple and basic |
| 62 |
dynamic dispatch technique. |
| 63 |
|
| 64 |
|
| 65 |
== Dynamic Dispatch Using a Recursive Record of Functions |
| 66 |
|
| 67 |
Quite simply, the basic idea is to implement a "virtual function |
| 68 |
table" using a record that is wrapped inside a (possibly recursive) |
| 69 |
datatype. Let's first take a look at a simple concrete example. |
| 70 |
|
| 71 |
Consider the following Java interface: |
| 72 |
|
| 73 |
---- |
| 74 |
public interface Counter { |
| 75 |
public void inc(); |
| 76 |
public int get(); |
| 77 |
} |
| 78 |
---- |
| 79 |
|
| 80 |
We can translate the `Counter` interface to SML as follows: |
| 81 |
|
| 82 |
[source,sml] |
| 83 |
---- |
| 84 |
datatype counter = Counter of {inc : unit -> unit, get : unit -> int} |
| 85 |
---- |
| 86 |
|
| 87 |
Each value of type `counter` can be thought of as an object that |
| 88 |
responds to two messages `inc` and `get`. To actually send messages |
| 89 |
to a counter, it is useful to define auxiliary functions |
| 90 |
|
| 91 |
[source,sml] |
| 92 |
---- |
| 93 |
local |
| 94 |
fun mk m (Counter t) = m t () |
| 95 |
in |
| 96 |
val cGet = mk#get |
| 97 |
val cInc = mk#inc |
| 98 |
end |
| 99 |
---- |
| 100 |
|
| 101 |
that basically extract the "function table" `t` from a counter object |
| 102 |
and then select the specified method `m` from the table. |
| 103 |
|
| 104 |
Let's then implement a simple function that increments a counter until a |
| 105 |
given maximum is reached: |
| 106 |
|
| 107 |
[source,sml] |
| 108 |
---- |
| 109 |
fun incUpto counter max = while cGet counter < max do cInc counter |
| 110 |
---- |
| 111 |
|
| 112 |
You can easily verify that the above code compiles even without any |
| 113 |
concrete implementation of a counter, thus it is clear that it doesn't |
| 114 |
depend on a particular counter implementation. |
| 115 |
|
| 116 |
Let's then implement a couple of counters. First consider the |
| 117 |
following Java class implementing the `Counter` interface given earlier. |
| 118 |
|
| 119 |
---- |
| 120 |
public class BasicCounter implements Counter { |
| 121 |
private int cnt; |
| 122 |
public BasicCounter(int initialCnt) { this.cnt = initialCnt; } |
| 123 |
public void inc() { this.cnt += 1; } |
| 124 |
public int get() { return this.cnt; } |
| 125 |
} |
| 126 |
---- |
| 127 |
|
| 128 |
We can translate the above to SML as follows: |
| 129 |
|
| 130 |
[source,sml] |
| 131 |
---- |
| 132 |
fun newBasicCounter initialCnt = let |
| 133 |
val cnt = ref initialCnt |
| 134 |
in |
| 135 |
Counter {inc = fn () => cnt := !cnt + 1, |
| 136 |
get = fn () => !cnt} |
| 137 |
end |
| 138 |
---- |
| 139 |
|
| 140 |
The SML function `newBasicCounter` can be described as a constructor |
| 141 |
function for counter objects of the `BasicCounter` "class". We can |
| 142 |
also have other counter implementations. Here is the constructor for |
| 143 |
a counter decorator that logs messages: |
| 144 |
|
| 145 |
[source,sml] |
| 146 |
---- |
| 147 |
fun newLoggedCounter counter = |
| 148 |
Counter {inc = fn () => (print "inc\n" ; cInc counter), |
| 149 |
get = fn () => (print "get\n" ; cGet counter)} |
| 150 |
---- |
| 151 |
|
| 152 |
The `incUpto` function works just as well with objects of either |
| 153 |
class: |
| 154 |
|
| 155 |
[source,sml] |
| 156 |
---- |
| 157 |
val aCounter = newBasicCounter 0 |
| 158 |
val () = incUpto aCounter 5 |
| 159 |
val () = print (Int.toString (cGet aCounter) ^"\n") |
| 160 |
|
| 161 |
val aCounter = newLoggedCounter (newBasicCounter 0) |
| 162 |
val () = incUpto aCounter 5 |
| 163 |
val () = print (Int.toString (cGet aCounter) ^"\n") |
| 164 |
---- |
| 165 |
|
| 166 |
In general, a dynamic dispatch interface is represented as a record |
| 167 |
type wrapped inside a datatype. Each field of the record corresponds |
| 168 |
to a public method or field of the object: |
| 169 |
|
| 170 |
[source,sml] |
| 171 |
---- |
| 172 |
datatype interface = |
| 173 |
Interface of {method : t1 -> t2, |
| 174 |
immutableField : t, |
| 175 |
mutableField : t ref} |
| 176 |
---- |
| 177 |
|
| 178 |
The reason for wrapping the record inside a datatype is that records, |
| 179 |
in SML, can not be recursive. However, SML datatypes can be |
| 180 |
recursive. A record wrapped in a datatype can contain fields that |
| 181 |
contain the datatype. For example, an interface such as `Cloneable` |
| 182 |
|
| 183 |
[source,sml] |
| 184 |
---- |
| 185 |
datatype cloneable = Cloneable of {clone : unit -> cloneable} |
| 186 |
---- |
| 187 |
|
| 188 |
can be represented using recursive datatypes. |
| 189 |
|
| 190 |
Like in OO languages, interfaces are abstract and can not be |
| 191 |
instantiated to produce objects. To be able to instantiate objects, |
| 192 |
the constructors of a concrete class are needed. In SML, we can |
| 193 |
implement constructors as simple functions from arbitrary arguments to |
| 194 |
values of the interface type. Such a constructor function can |
| 195 |
encapsulate arbitrary private state and functions using lexical |
| 196 |
closure. It is also easy to share implementations of methods between |
| 197 |
two or more constructors. |
| 198 |
|
| 199 |
While the `Counter` example is rather trivial, it should not be |
| 200 |
difficult to see that this technique quite simply doesn't require a huge |
| 201 |
amount of extra verbiage and is more than usable in practice. |
| 202 |
|
| 203 |
|
| 204 |
== SML Modules and Dynamic Dispatch |
| 205 |
|
| 206 |
One might wonder about how SML modules and the dynamic dispatch |
| 207 |
technique work together. Let's investigate! Let's use a simple |
| 208 |
dispenser framework as a concrete example. (Note that this isn't |
| 209 |
intended to be an introduction to the SML module system.) |
| 210 |
|
| 211 |
=== Programming with SML Modules |
| 212 |
|
| 213 |
Using SML signatures we can specify abstract data types (ADTs) such as |
| 214 |
dispensers. Here is a signature for an "abstract" functional (as |
| 215 |
opposed to imperative) dispenser: |
| 216 |
|
| 217 |
[source,sml] |
| 218 |
---- |
| 219 |
signature ABSTRACT_DISPENSER = sig |
| 220 |
type 'a t |
| 221 |
val isEmpty : 'a t -> bool |
| 222 |
val push : 'a * 'a t -> 'a t |
| 223 |
val pop : 'a t -> ('a * 'a t) option |
| 224 |
end |
| 225 |
---- |
| 226 |
|
| 227 |
The term "abstract" in the name of the signature refers to the fact that |
| 228 |
the signature gives no way to instantiate a dispenser. It has nothing to |
| 229 |
do with the concept of abstract data types. |
| 230 |
|
| 231 |
Using SML functors we can write "generic" algorithms that manipulate |
| 232 |
dispensers of an unknown type. Here are a couple of very simple |
| 233 |
algorithms: |
| 234 |
|
| 235 |
[source,sml] |
| 236 |
---- |
| 237 |
functor DispenserAlgs (D : ABSTRACT_DISPENSER) = struct |
| 238 |
open D |
| 239 |
|
| 240 |
fun pushAll (xs, d) = foldl push d xs |
| 241 |
|
| 242 |
fun popAll d = let |
| 243 |
fun lp (xs, NONE) = rev xs |
| 244 |
| lp (xs, SOME (x, d)) = lp (x::xs, pop d) |
| 245 |
in |
| 246 |
lp ([], pop d) |
| 247 |
end |
| 248 |
|
| 249 |
fun cp (from, to) = pushAll (popAll from, to) |
| 250 |
end |
| 251 |
---- |
| 252 |
|
| 253 |
As one can easily verify, the above compiles even without any concrete |
| 254 |
dispenser structure. Functors essentially provide a form a static |
| 255 |
dispatch that one can use to break compile-time dependencies. |
| 256 |
|
| 257 |
We can also give a signature for a concrete dispenser |
| 258 |
|
| 259 |
[source,sml] |
| 260 |
---- |
| 261 |
signature DISPENSER = sig |
| 262 |
include ABSTRACT_DISPENSER |
| 263 |
val empty : 'a t |
| 264 |
end |
| 265 |
---- |
| 266 |
|
| 267 |
and write any number of concrete structures implementing the signature. |
| 268 |
For example, we could implement stacks |
| 269 |
|
| 270 |
[source,sml] |
| 271 |
---- |
| 272 |
structure Stack :> DISPENSER = struct |
| 273 |
type 'a t = 'a list |
| 274 |
val empty = [] |
| 275 |
val isEmpty = null |
| 276 |
val push = op :: |
| 277 |
val pop = List.getItem |
| 278 |
end |
| 279 |
---- |
| 280 |
|
| 281 |
and queues |
| 282 |
|
| 283 |
[source,sml] |
| 284 |
---- |
| 285 |
structure Queue :> DISPENSER = struct |
| 286 |
datatype 'a t = T of 'a list * 'a list |
| 287 |
val empty = T ([], []) |
| 288 |
val isEmpty = fn T ([], _) => true | _ => false |
| 289 |
val normalize = fn ([], ys) => (rev ys, []) | q => q |
| 290 |
fun push (y, T (xs, ys)) = T (normalize (xs, y::ys)) |
| 291 |
val pop = fn (T (x::xs, ys)) => SOME (x, T (normalize (xs, ys))) | _ => NONE |
| 292 |
end |
| 293 |
---- |
| 294 |
|
| 295 |
One can now write code that uses either the `Stack` or the `Queue` |
| 296 |
dispenser. One can also instantiate the previously defined functor to |
| 297 |
create functions for manipulating dispensers of a type: |
| 298 |
|
| 299 |
[source,sml] |
| 300 |
---- |
| 301 |
structure S = DispenserAlgs (Stack) |
| 302 |
val [4,3,2,1] = S.popAll (S.pushAll ([1,2,3,4], Stack.empty)) |
| 303 |
|
| 304 |
structure Q = DispenserAlgs (Queue) |
| 305 |
val [1,2,3,4] = Q.popAll (Q.pushAll ([1,2,3,4], Queue.empty)) |
| 306 |
---- |
| 307 |
|
| 308 |
There is no dynamic dispatch involved at the module level in SML. An |
| 309 |
attempt to do dynamic dispatch |
| 310 |
|
| 311 |
[source,sml] |
| 312 |
---- |
| 313 |
val q = Q.push (1, Stack.empty) |
| 314 |
---- |
| 315 |
|
| 316 |
will give a type error. |
| 317 |
|
| 318 |
=== Combining SML Modules and Dynamic Dispatch |
| 319 |
|
| 320 |
Let's then combine SML modules and the dynamic dispatch technique |
| 321 |
introduced in this article. First we define an interface for |
| 322 |
dispensers: |
| 323 |
|
| 324 |
[source,sml] |
| 325 |
---- |
| 326 |
structure Dispenser = struct |
| 327 |
datatype 'a t = |
| 328 |
I of {isEmpty : unit -> bool, |
| 329 |
push : 'a -> 'a t, |
| 330 |
pop : unit -> ('a * 'a t) option} |
| 331 |
|
| 332 |
fun O m (I t) = m t |
| 333 |
|
| 334 |
fun isEmpty t = O#isEmpty t () |
| 335 |
fun push (v, t) = O#push t v |
| 336 |
fun pop t = O#pop t () |
| 337 |
end |
| 338 |
---- |
| 339 |
|
| 340 |
The `Dispenser` module, which we can think of as an interface for |
| 341 |
dispensers, implements the `ABSTRACT_DISPENSER` signature using |
| 342 |
the dynamic dispatch technique, but we leave the signature ascription |
| 343 |
until later. |
| 344 |
|
| 345 |
Then we define a `DispenserClass` functor that makes a "class" out of |
| 346 |
a given dispenser module: |
| 347 |
|
| 348 |
[source,sml] |
| 349 |
---- |
| 350 |
functor DispenserClass (D : DISPENSER) : DISPENSER = struct |
| 351 |
open Dispenser |
| 352 |
|
| 353 |
fun make d = |
| 354 |
I {isEmpty = fn () => D.isEmpty d, |
| 355 |
push = fn x => make (D.push (x, d)), |
| 356 |
pop = fn () => |
| 357 |
case D.pop d of |
| 358 |
NONE => NONE |
| 359 |
| SOME (x, d) => SOME (x, make d)} |
| 360 |
|
| 361 |
val empty = |
| 362 |
I {isEmpty = fn () => true, |
| 363 |
push = fn x => make (D.push (x, D.empty)), |
| 364 |
pop = fn () => NONE} |
| 365 |
end |
| 366 |
---- |
| 367 |
|
| 368 |
Finally we seal the `Dispenser` module: |
| 369 |
|
| 370 |
[source,sml] |
| 371 |
---- |
| 372 |
structure Dispenser : ABSTRACT_DISPENSER = Dispenser |
| 373 |
---- |
| 374 |
|
| 375 |
This isn't necessary for type safety, because the unsealed `Dispenser` |
| 376 |
module does not allow one to break encapsulation, but makes sure that |
| 377 |
only the `DispenserClass` functor can create dispenser classes |
| 378 |
(because the constructor `Dispenser.I` is no longer accessible). |
| 379 |
|
| 380 |
Using the `DispenserClass` functor we can turn any concrete dispenser |
| 381 |
module into a dispenser class: |
| 382 |
|
| 383 |
[source,sml] |
| 384 |
---- |
| 385 |
structure StackClass = DispenserClass (Stack) |
| 386 |
structure QueueClass = DispenserClass (Queue) |
| 387 |
---- |
| 388 |
|
| 389 |
Each dispenser class implements the same dynamic dispatch interface |
| 390 |
and the `ABSTRACT_DISPENSER` -signature. |
| 391 |
|
| 392 |
Because the dynamic dispatch `Dispenser` module implements the |
| 393 |
`ABSTRACT_DISPENSER`-signature, we can use it to instantiate the |
| 394 |
`DispenserAlgs`-functor: |
| 395 |
|
| 396 |
[source,sml] |
| 397 |
---- |
| 398 |
structure D = DispenserAlgs (Dispenser) |
| 399 |
---- |
| 400 |
|
| 401 |
The resulting `D` module, like the `Dispenser` module, works with |
| 402 |
any dispenser class and uses dynamic dispatch: |
| 403 |
|
| 404 |
[source,sml] |
| 405 |
---- |
| 406 |
val [4, 3, 2, 1] = D.popAll (D.pushAll ([1, 2, 3, 4], StackClass.empty)) |
| 407 |
val [1, 2, 3, 4] = D.popAll (D.pushAll ([1, 2, 3, 4], QueueClass.empty)) |
| 408 |
---- |