Oct 19, 2006 22:11
I think I've written the most polymorphic non-toy two-line ML program ever.
val cross : (('a -> 'b -> 'c) -> 'd -> 'e -> 'f) ->
(('g -> 'h -> 'i) -> 'j -> 'b -> 'c) ->
('a -> 'g -> 'h -> 'i) ->
'e -> 'd -> 'j -> 'f
Here's the definition:
let cross outer inner f init xs ys =
outer (fun x acc -> inner (fun y acc -> f x y acc) ys acc) xs init
It encapsulates a nested iteration over two arbitrary collections. The first two arguments are folds over two different datatypes, the third and forth arguments are the step function and initial argument, and the last two are the two collections. I am tempted to try and generalize this so it's a combinator that lets you iterate over an arbitrary number of collections, but that seems over the top -- I've already got 10 polymorphic arguments!