xtransform.cd 1.99 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36

(* For the purpose of the example we can consider this hugely
   simplified definition of Xhtml
*)



type Flow = Char | Block | Inline  ;;
type Block = P | Heading | Lists | Blocktext | Char
type Lists = Ul
type Blocktext = Pre |  Address | Center;;
type Inline = Char | A | Fontstyle
type Fontstyle = Tt | I | B | Big | Small;;

type Xhtml = <html>[ Head Body ];;
type Head = <head>[ Title <link>[ ]];;
type Title = <title>[ PCDATA ];;
type Body = <body bgcolor=?String>[ Block* ];;

type P = <p>[ Inline* ];;
type Heading = <(`h1 | `h2 | `h3 | `h4)>[ Inline* ];;

type Ul = <ul>[Li+];;
type Li = <li>[ Flow* ];;

type Address = <address>[ Inline* ];;
type Pre = <pre>[ (PCDATA | A | Fontstyle)* ];;
type Center = <center>[ Block* ];;

type A = <a ({ name = String } | { href = String })>[ (Inline \ A)* ];;
type Tt = <tt>[ Inline* ];;
type I = <i>[ Inline* ];;
type B = <b>[ Inline* ];;
type Big = <big>[ Inline* ];;
type Small = <small>[ Inline* ];;

37 38 39 40 41 42 43 44 45
(* xtransform matches the patterns against the root element of each
   XML tree and, if it fails, it recursively applies itself to the
   sequence of sons of the root.

   It can be used to put in boldface all the links of an XHTML
   document as follows
*)


46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79


let bold(x:[Xhtml]):[Xhtml]=xtransform x with <a (y)>t -> [ <a(y)>[<b>t] ]

(* let us apply the function to a document where links appear
   at different depths
*)


let doc : Xhtml =
  <html>[
    <head>[<title>"Example" <link>[]]
    <body>[
      <h2>['You can have links ' <a href="here">"here"]
      <p>['Or they can be down']
      <ul>[
        <li>['In ' <a name="list">"lists" ' for instance']
	<li>['or you oddly decided to ' 
             <center>[<p>[<a href="what?">"center"]] 
             ' them '
            ]
      ]
     <address>[
        'and even if they are in fancy ' <a name="address">"address boxes"
     ]
     <p>['nevertheless ' <a href="http://www.cduce.org">"Cduce" ' and '
         <a href="xtransform">[<tt>"xtransform"] ' will put all links in bold ']
    ]
  ];;

bold [doc];;

match