## 4663Re: "ocaml_beginners"::[] mutually recursive definition of non-function values

Expand Messages
• Oct 2, 2005
On Sun, 2 Oct 2005, Seth J. Fogarty wrote:

> On 10/2/05, a22_19_22 <a22_19_22@...> wrote:
>> . . .
>> No, the behavior is /very/ well defined. Just not terribly useful.
>>
>> I gotta put my \$.02 in here (I think there was a brief mention of
>> cyclic lists in this forum a week or two ago). Cyclic lists can be
>> very useful, just not very often. Off the top of my head:
>
> Well, I stand gladly corrected.
>
>> OCaml does make it harder (needlessly IMHO) to use circular lists by
>> raising an exception if the list arguments to two-list iterators such
>> as List.map2 and List.fold_left2 are not of the same length. When
>> lists of different length are allowed, it can be convenient to map or
>> fold over an ordinary list and a circular list.
>
> These shouldn't be terribly hard to rewrite this way... it's a bit of
> a strange way of thinking about them, but it's very doable. Map and
> fold are four-line functions, and I doubt map2 and fold2 are much
> longer.

No, they're not:

let rec fold_left2' f init alist blist =
match alist, blist with
| (ah::at), (bh::bt) -> fold_left2' f (f init ah bh) at bt
| _ -> init
;;

let rec fold_right2' f alist blist init =
(* NOT tail recursive *)
match alist, blist with
| (ah::at), (bh::bt) -> f ah bh (fold_right2' f at bt init)
| _ -> init
;;

let map2' f alist blist =
let rec loop accum alist blist =
match alist, blist with
| (ah::at), (bh::bt) -> loop ((f ah bh) :: accum) at bt
| _ -> List.rev accum
in
loop [] alist blist
;;

Brian
• Show all 15 messages in this topic