Version française
Home     About     Download     Resources     Contact us    

This site is updated infrequently. For up-to-date information, please visit the new OCaml website at

Browse thread
[Caml-list] two unrelated questions
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: 2001-04-26 (00:40)
From: Patrick M Doane <patrick@w...>
Subject: Re: [Caml-list] two unrelated questions
On Wed, 25 Apr 2001, Chris Hecker wrote:

> 1.  What is the right "functional pattern" for early-outing on success
>     while using an iter/map/fold type function?  Say I'm using iter to
>     search for something in an opaque datastructure.  Should I throw
>     an exception to get out, or is that bad style?  I guess this
>     question only makes sense for iter, since map/fold produce results
>     that you theoretically want to preserve.  So, the question is
>     really, given an iter-style interface to a datastructure (one that
>     takes an ('a -> unit)), how do you tell it to stop iterating?  I
>     guess if the function was ('a -> bool) you could do it that way,
>     but most iters aren't ((List|Array|Hashtbl).iter, for example).
>     Is throwing an exception the best bet?

One way to think about exceptions is to treat them simply as control flow
expressions. For example, the 'break' statement is used in C/C++ to
early-out of iteration constructs. This translates naturally to

  exception Break
    List.iter (fun ..  -> ...  raise Break) l
  with Break -> ()

We can even get labelled breaks like Java:

  exception Break of string
    List.iter (fun ... ->
        List.iter (fun ... ->
          if .. then raise (Break "inner")
                else raise (Break "outer")
        ) list1
      with Break "inner" -> ()
    ) list2
  with Break "outer" -> ()

I personally don't think this is bad style but others may have a different

It also seems that the overhead for a try block in Caml is relatively low,
but I've never looked too much at the compiled code to see what it is


To unsubscribe, mail  Archives: