🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: alt.lang.ml
Article #4

Re: can this be implemented in O(1) space?

#4
From: Marc Najork
Date: Mon, 06 Apr 1992 18:14
31 lines
1420 bytes
In article <1992Apr06.025126.33552@slate.mines.colorado.edu>, jgore@Mines.Colorado.Edu (Jacob Gore) writes:
> Consider the following function for computing x to the power of n:
> 
> fun power(x,n) =
>   if n=0 then 1.0
>   else if n mod 2 = 1 then x * power(x,n-1)
>   else power(x*x, n div 2);
> 
> What is the likelihood of an SML implementation doing it in O(1) space?
> 
> Jacob
> --
> Jacob Gore			Mathematical and Computer Sciences
> <JGore@Mines.Colorado.Edu>	Colorado School of Mines
> 
> 	-- Member of the League for Programming Freedom --

If you transform this into a tail-recursive form, i.e.

        fun power(x,n) =
          auxpower(x,n,1.0);

        fun auxpower(x,n,res) =
          if n=0 then res
          else if n mod 2 = 1 then power(x,n-1,res*x)
          else power(x*x, n div 2,res);

then a good compiler should recognize that it is a tail-recursion, and
convert it into an iterative form, which would need constant space.

-- Marc Najork
Technical Details
Message-ID: <1992Apr6.181407.30174@m.cs.uiuc.edu>
Path: arc1-ca.pugleaf.net!sparky!uunet!wupost!m.cs.uiuc.edu!uiucdcs!najork
References: <1992Apr06.025126.33552@slate.mines.colorado.edu>

Show Full Headers
Complete Article Headers
Newsgroups: alt.lang.ml
Path: arc1-ca.pugleaf.net!sparky!uunet!wupost!m.cs.uiuc.edu!uiucdcs!najork
From: najork@cs.uiuc.edu (Marc Najork)
Subject: Re: can this be implemented in O(1) space?
Message-ID: <1992Apr6.181407.30174@m.cs.uiuc.edu>
Sender: news@m.cs.uiuc.edu (News Database (admin-Mike Schwager))
Organization: Delta Group
References:  <1992Apr06.025126.33552@slate.mines.colorado.edu>
Date: Mon, 6 Apr 1992 18:14:07 GMT