From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: X-Original-To: caml-list@yquem.inria.fr Delivered-To: caml-list@yquem.inria.fr Received: from nez-perce.inria.fr (nez-perce.inria.fr [192.93.2.78]) by yquem.inria.fr (Postfix) with ESMTP id DACD1BB84 for ; Mon, 17 Apr 2006 15:09:37 +0200 (CEST) Received: from smtp2-g19.free.fr (smtp2-g19.free.fr [212.27.42.28]) by nez-perce.inria.fr (8.13.0/8.13.0) with ESMTP id k3HD9bsa012503 for ; Mon, 17 Apr 2006 15:09:37 +0200 Received: from [192.168.1.2] (che78-2-82-237-71-191.fbx.proxad.net [82.237.71.191]) by smtp2-g19.free.fr (Postfix) with ESMTP id 59ECC6FECE; Mon, 17 Apr 2006 15:09:37 +0200 (CEST) Message-ID: <44439390.7040102@inria.fr> Date: Mon, 17 Apr 2006 15:09:36 +0200 From: Xavier Leroy User-Agent: Mozilla Thunderbird 1.0.2 (X11/20050317) X-Accept-Language: en-us, en MIME-Version: 1.0 To: Tato Thetza Cc: caml-list@yquem.inria.fr Subject: Re: [Caml-list] recursion/iterator question References: <1145221898.16349.259200911@webmail.messagingengine.com> In-Reply-To: <1145221898.16349.259200911@webmail.messagingengine.com> X-Enigmail-Version: 0.91.0.0 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: 7bit X-Miltered: at nez-perce with ID 44439391.000 by Joe's j-chkmail (http://j-chkmail.ensmp.fr)! X-Spam: no; 0.00; recursion:01 iterator:01 uncommon:01 syntax:01 caml-list:01 int:01 int:01 tend:02 let:03 expressions:04 extension:05 iterate:06 inria:06 fold:06 fold:06 X-Spam-Checker-Version: SpamAssassin 3.0.3 (2005-04-27) on yquem.inria.fr X-Spam-Level: X-Spam-Status: No, score=0.0 required=5.0 tests=none autolearn=disabled version=3.0.3 > Given a list, I would like to iterate over all triplets in the list. For > example, in mathematcs, its not uncommon to have expressions such as > "for all i,j,k in set X, do f(i,j,k)" > > The only way I can think of is to create a list with all triplets of the > list, so: > triplets([1,2,3,4]) = [(1,2,3),(1,2,4),(1,3,4),(2,3,4)] > and take this list and map a function f to it. Folds are more general than maps and tend to compose better. Consider: let list_fold_right_3 f l1 l2 l3 = List.fold_right (fun x1 -> List.fold_right (fun x2 -> List.fold_right (f x1 x2) l3) l2) l1 Examples: # list_fold_right_3 (fun x y z a -> (x,y,z)::a) [1;2] [3;4] [5;6] [];; - : (int * int * int) list = [(1, 3, 5); (1, 3, 6); (1, 4, 5); (1, 4, 6); (2, 3, 5); (2, 3, 6); (2, 4, 5); (2, 4, 6)] # list_fold_right_3 (fun x y z a -> (x+y+z)::a) [1;2] [3;4] [5;6] [];; - : int list = [9; 10; 10; 11; 10; 11; 11; 12] # list_fold_right_3 (fun x y z a -> x*y*z + a) [1;2] [3;4] [5;6] 0;; - : int = 231 But, yes, if you find yourself doing this often, it's a good idea to use the syntax extension for list comprehensions. - Xavier Leroy