Version française
Home     About     Download     Resources     Contact us    
Browse thread
problems with the new camlp4 (again)
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Bruno De Fraine <Bruno.De.Fraine@v...>
Subject: Re: [Caml-list] problems with the new camlp4 (again)

On 03 Jul 2007, at 21:59, Benedikt Grundmann wrote:
> description would be ("Bar", 2)
>
> generated functions:
>
> let wrap (a, b) = Bar (a,b)
>
> let unwrap (Bar (a, b)) = (a, b)

Given a function to generate variable names:

let var_name =
   let b = int_of_char 'a' in
   fun i -> String.make 1 (char_of_int (b+i))
;;

and some copy-pasted auxiliary functions:

let rec fold_range f accu l u =
   if l < u then let u = u - 1 in fold_range f (f accu u) l u else accu
;;

let lid_patt _loc n = <:patt< $lid:n$ >> ;;
let lid_expr _loc n = <:expr< $lid:n$ >> ;;

let tuple_patt _loc = function
   | [] -> <:patt< () >>
   | [p] -> p
   | p::ps -> <:patt< ($p$,$list:ps$) >>
;;

let expr_of_cons _loc n es =
   List.fold_left (fun acc e ->
     <:expr< $acc$ $e$ >>
   ) <:expr< $uid:n$ >> es
;;

This is quite trivial:

let gen_wrap _loc (n,i) =
   let var_names = fold_range (fun l c -> (var_name c)::l) [] 0 i in
   let
     patt = tuple_patt _loc (List.map (lid_patt _loc) var_names) and
     expr = expr_of_cons _loc n (List.map (lid_expr _loc) var_names)
   in <:expr< fun $patt$ -> $expr$ >>
;;

Test:

# let _loc = Loc.ghost in
   (gen_wrap _loc ("Bar",2) = <:expr< fun (a,b) -> Bar a b >>) ;;
- : bool = true

I'll leave "gen_unwrap" as an exercise.

Regards,
Bruno

--
Bruno De Fraine
Vrije Universiteit Brussel
Faculty of Applied Sciences, DINF - SSEL
Room 4K208, Pleinlaan 2, B-1050 Brussels
tel: +32 (0)2 629 29 75
fax: +32 (0)2 629 28 70
e-mail: Bruno.De.Fraine@vub.ac.be