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 BCD91BB81 for ; Mon, 13 Feb 2006 00:52:13 +0100 (CET) Received: from kurims.kurims.kyoto-u.ac.jp (kurims.kurims.kyoto-u.ac.jp [130.54.16.1]) by nez-perce.inria.fr (8.13.0/8.13.0) with ESMTP id k1CNqBWY005377 for ; Mon, 13 Feb 2006 00:52:13 +0100 Received: from localhost (suiren [130.54.16.25]) by kurims.kurims.kyoto-u.ac.jp (8.13.1/8.13.1) with ESMTP id k1CNq7e0007018; Mon, 13 Feb 2006 08:52:08 +0900 (JST) Date: Mon, 13 Feb 2006 08:53:48 +0900 (JST) Message-Id: <20060213.085348.126575598.garrigue@math.nagoya-u.ac.jp> To: jonathan.roewen@gmail.com Cc: caml-list@yquem.inria.fr Subject: Re: [Caml-list] HOFs, recursion, and being tail-rec... From: Jacques Garrigue In-Reply-To: References: X-Mailer: Mew version 4.2 on Emacs 21.3 / Mule 5.0 (SAKAKI) Mime-Version: 1.0 Content-Type: Text/Plain; charset=us-ascii Content-Transfer-Encoding: 7bit X-Miltered: at nez-perce with ID 43EFCA2B.001 by Joe's j-chkmail (http://j-chkmail.ensmp.fr)! X-Spam: no; 0.00; caml-list:01 hofs:01 recursion:01 ocaml:01 optimise:01 stack:01 backtracking:01 nodes:01 val:01 omitting:01 nodes:01 val:01 dfs:01 bool:01 dfs:01 X-Spam-Checker-Version: SpamAssassin 3.0.3 (2005-04-27) on yquem.inria.fr X-Spam-Level: X-Spam-Status: No, score=0.4 required=5.0 tests=DNS_FROM_RFC_ABUSE autolearn=disabled version=3.0.3 From: Jonathan Roewen > > I have a simple implementation of depth-first-search, and was > wondering if my approach would qualify as tail-rec (whether from the > code it is/isn't, and whether ocaml can optimise it so it is). By definition a depth-first-search cannot be tail-recursive: you need a stack to implement the backtracking. There is a degenerate case where all nodes are non-branching (i.e. there is only one path), which in theory could be made tail-recursive. But it would not be the case with your code, as List.exists has no special case for the last element of the list (not that it would make a lot of sense in general.) > val positions : 'a -> ('a * 'a) list -> 'a list -> 'a list > (* I think that's right type: returns positions we can traverse to, > omitting nodes we've previously visited *) > > (* val dfs: 'a -> 'a -> ('a * 'a) list -> bool *) > let dfs start goal edges = > let rec search visited position = > if position = goal then true > else List.exists (search (position::visited)) (positions > position edges (position::visited)) > in search [] start;;