Version française
Home     About     Download     Resources     Contact us    

This site is updated infrequently. For up-to-date information, please visit the new OCaml website at

Browse thread
RE: Functional composition operator?
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: 1998-12-09 (09:11)
From: John Prevost <j.prevost@c...>
Subject: RE: Functional composition operator?
On Tue, 8 Dec 1998, Andrew Kay wrote:

> In the end we settled on >> and << for forward and reverse
> composition respectively, satisfying the equations:
> We're still interested to know if other people have different approaches.

This seems to be a very reasonable approach!  I'd been thinking recently
about this very question, and also about reverse composition, and the
chevrons handle this distinction quite nicely.

As for the person who said that composition isn't necessary:  there are
places where it is useful, in any case.  Take the following example of
an extensible printf system using continuation-passing in O'Caml
(translated from an SML version shown to me by Franklin Chen):

let id x = x

(* continuation, string, args *)
let f_int    k s x = k (s ^ string_of_int x)

let f_str    k s x = k (s ^ x)

let f_lit  x k s   = k (s ^ x)

let f_eol    k s   = k (s ^ "\n")

let f_list t k s = function
                   | [] -> k (s ^ "[]")
                   | xs -> let rec loop l k s =
                       match l with
                        | [x] ->     t (fun s -> k (s ^ "]")) s x
                        | (x::xs) -> t (fn s => loop xs k (s ^ ", ")) s x
                     in loop xs k (s ^ "[")

let printf c = c id ""

(* "3 is foo[2, 3, 4]\n" *)
let foo =
  printf (f_int $ f_lit " is " $ f_str $ (f_lis f_int) $ f_eol)
    3 "foo" [2, 3, 4];;

where $ is normal functional composition.

Notice that this definition of formatting has similar (although not
exactly the same, because it only support writing out a string (this
could be fixed, and possibly in a generic way)) nice properties to
O'Caml's Printf.printf stuff and formats, but doesn't require the
compiler to know about a special type of formats.  Note also that
composition serves a very good purpose in this case--you couldn't do
this easily without it, or with a prefix composition operator.