English version
Accueil     À propos     Téléchargement     Ressources     Contactez-nous    

Ce site est rarement mis à jour. Pour les informations les plus récentes, rendez-vous sur le nouveau site OCaml à l'adresse ocaml.org.

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: 2001-05-12 (05:53)
From: Miles Egan <miles@c...>
Subject: [Caml-list] recursive variants
I'm trying to translate a simple random sentence generator from lisp to ocaml
and I'm having a bit of trouble with the types.  Here's what I have so far:

type grammar_element =
  Word of string
| Wordlist of string list
| Phrase of (unit -> string list)
| Phraselist of (unit -> string list) list

let split str =
  Str.split (Str.regexp "[ \t]") str

let random_elt choices =
  (*Choose an element from a list at random.*)
  List.nth choices (Random.int (List.length choices))

let one_of set =
  (*Pick one element of set, and make a list of it.*)
  [random_elt set]

let pick_word str =
  one_of (split str)

let adj () =
  pick_word "big little blue green adiabatic"

let prep () =
  pick_word "to in by with on"

let article () =
  pick_word "the a"

let noun () =
  pick_word "man ball woman table"

let noun_phrase () =
  List.append (article ()) (noun ())

let verb () =
  pick_word "hit took saw liked"

let verb_phrase () =
  List.append (verb ()) (noun_phrase ())

let sentence () =
  List.append (noun_phrase ()) (verb_phrase ())    

let simple_grammar = 
  (* A grammar for a trivial subset of English. *)
  [ (Phrase sentence, Phraselist [noun_phrase; verb_phrase]);
    (Phrase noun_phrase, Phraselist [article; noun]);
    (Phrase verb_phrase, Phraselist [verb; noun_phrase]);
    (Phrase article, Wordlist (split "the a"));
    (Phrase noun, Wordlist (split "man ball woman table"));
    (Phrase verb, Wordlist (split "hit took saw liked")); ]

let rewrites category =
  (* Return a list of the possible rewrites for this category. *)
  List.find (fun (a,b) -> a = category) simple_grammar

let rec generate phrase =
  (* Generate a random sentence or phrase *)
  match phrase with 
    Phraselist p -> List.map generate p
  | Phrase p -> (one_of (rewrites p)) ()
  | Wordlist p -> one_of p
  | Word p -> p

This generates an error in 'generate' because List.map is called on the matched
Phraselist p, which isn't a grammar_element, but a (unit -> string list) list.

What I want to do is this:

type grammar_element =
  Word of string
| Wordlist of Word list
| Phrase of unit -> Wordlist
| Phraselist of Phrase list

But this doesn't seem to be legal.  I suppose this is pretty basic stuff, but
I'm stuck.  Any suggestions?

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