Browse thread
Reference to polymorphic function ?
[
Home
]
[ Index:
by date
|
by threads
]
[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
| Date: | -- (:) |
| From: | Ingo Bormuth <ibormuth@e...> |
| Subject: | [SOLVED] Reference to polymorphic function ? |
On 2005-09-15 08:48, Jacques Garrigue wrote:
>
> The simplest way to do this is to define a new type:
>
> type put = {put: 'a -> unit} ;;
> let put = {put = put_to_screen} ;;
> put.put "test";;
> put.put 5;;
>
Thank you !!! That's exactly what I was looking for.
On 2005-09-14 23:08, Stéphane Glondu wrote:
>
> However, I didn't catch what
> you want to do with thoses references: maybe there is another way to
> achieve what you want?
>
Just for the notes:
I wrote a serilisation function to pack a quite complex data structure
into one string. That string is then used to feed a file, socket,
sha1 or encryption algorithm.
I want to reduce overhead and directly marshal the values to the
destination without generating the intermediate string whenever possible.
This is a simple profe of principal prototype :
type data =
| Int of int
| Float of float
| Str of string
;;
type target =
| Screen
| Channel of out_channel
;;
type put =
{
str: string -> unit ;
raw: 'a. 'a -> unit
}
;;
let serialize data target =
let put = ref {
str = ( fun s -> () );
raw = ( fun v -> () ) } in
let write_value key value =
!put.str ( "<" ^ key ^ ">" ) ;
!put.raw value ;
!put.str ( "</" ^ key ^ ">" ) in
let write_data () =
match data with
| Int i -> write_value "int" i
| Float f -> write_value "float" f
| Str s -> write_value "str" s in
let init_target =
match target with
| Screen -> put := {
str = print_string ;
raw = let f v = print_string ( Marshal.to_string v [] ) in f }
| Channel chan -> put := {
str = output_string chan ;
raw = let f v = ( Marshal.to_channel chan v [] ) in f } in
init_target ;
write_data ()
;;
serialize ( Int 123 ) Screen
;;
serialize ( Float 3.14 ) Screen
;;
serialize ( Str "Hello" ) ( Channel ( open_out "/tmp/seri" ) )
;;
--
+--------------------------------------------------------+
| Ingo Bormuth, voicebox & telefax: +49-12125-10226517 |
| GnuPG key 86326EC9 at http://ibormuth.efil.de/contact |
+--------------------------------------------------------+