Version française
Home     About     Download     Resources     Contact us    
Browse thread
[Caml-list] recursive variants
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Miles Egan <miles@c...>
Subject: Re: [Caml-list] recursive variants
On Sat, May 12, 2001 at 05:35:53PM +0200, Sven LUTHER wrote:
> type word = string
> type wordlist = string list
> type phrase = unit -> wordlist
> type phraselist = phrase list
> 
> and then :
> 
> type grammar_element =
> | Word of word
> | Wordlist of wordlist
> | Phrase of phrase
> | Phraselist of phraselist

I finally got this to work:

(*****************************************************)
type grammar_element =
  Word of string
| Term of (unit -> string)
| Nonterm of (unit -> grammar_element list)
| Terms of grammar_element list

let adj () =
  "big"

let prep () =
  "to"

let article () =
  "the"

let noun () =
  "man"

let verb () =
  "hit"

let noun_phrase () =
  [Term article; Term noun]

let verb_phrase () =
  [Term verb; Nonterm noun_phrase]

let sentence () =
  [Nonterm noun_phrase; Nonterm verb_phrase]

let rec generate part =
  match part with
  Terms p -> Terms (List.map generate p)
| Nonterm p -> generate (Terms (p ()))
| Term p -> Word (p ())
| Word p -> Word p

let _ =
  let s = generate (Nonterm sentence) in
  let rec printelem e =
    match e with
    Word w -> print_string (w ^ " ")
  | Term t -> print_string "term "
  | Nonterm t -> print_string "nonterm "
  | Terms t -> List.iter printelem t
  in
  match s with Terms t -> List.iter printelem t
(*****************************************************)

The trick was making sure that generate is of type (grammar_element ->
grammar_element) and defining a grammar_element such that a grammar_element list
is also a grammar_element list.  

This seems a bit cumbersome.  Is there a cleaner way to do this?  How do people
generally handle heterogeneous lists in ocaml?

-- 
miles
-------------------
To unsubscribe, mail caml-list-request@inria.fr.  Archives: http://caml.inria.fr