[
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: | 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
exceptions:
exception Break
try
List.iter (fun .. -> ... raise Break) l
with Break -> ()
We can even get labelled breaks like Java:
exception Break of string
try
List.iter (fun ... ->
try
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
opinion.
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
doing.
Patrick
-------------------
To unsubscribe, mail caml-list-request@inria.fr. Archives: http://caml.inria.fr