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

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Jon Harrop <jdh30@c...>
Subject: Re: [Caml-list] [ANN] The Missing Library
On Wednesday 28 April 2004 5:28 pm, skaller wrote:
[snip]
> let count = ref 0 in
> List.iter
> (fun x ->
>   if !start = 0 then
>   (start := 1; print "["; print x; )
>   else (print ";"; print x)
> )
> lst;
> if (!start <> 0) then print "]"

You mean:

let print_list string_of l = print_string ("["^(String.concat "; " (List.map 
string_of l))^"]")

Personally I'd factor out the making of and printing of the string. If you 
want a more "direct" conversion then just write a "list_mapi" function and 
test "i" each time.

> and please don't tell me that isn't a total mess compared with
> ...

Oh my God, you're not seriously advocating a page of gotos over that are you?

> Notice there are NO FLAGS. The entire state
> is represented by the program counter.
> In a more complex problem, the entire
> state can be local. You can even write
> a recursive procedure .. that builds a list  ..
> or even a tree .. do you want modify
> the external state like that, building
> a data structure to *emulate* a stack
> when you can actually have a real one?

I think you can easily have it either way in ocaml too. For the imperative 
style you can use map or iter with a function which has side-effects on some 
more global state. For the functional approach you use fold and pass the 
state on each time.

For example, I wrote this piece of code yesterday:

let rec eval bindings t = match t with
...
| Sequence l ->
    let f (bindings, l) t =
      let (bindings, t) = eval bindings t in (bindings, t::l) in
    let (bindings, l) = List.fold_left f (bindings, []) l in
    (bindings, Sequence (List.rev l))
| ...

It loops through a sequence of commands, executing each one in turn which may 
affect the current state "bindings" and the new state is passed on to the 
next command.

Cheers,
Jon.

-------------------
To unsubscribe, mail caml-list-request@inria.fr Archives: http://caml.inria.fr
Bug reports: http://caml.inria.fr/bin/caml-bugs FAQ: http://caml.inria.fr/FAQ/
Beginner's list: http://groups.yahoo.com/group/ocaml_beginners