On Sun, May 27, 2007 at 10:15:06AM +0900, Jon Harrop wrote:
> M. Edward (Ed) Borasky wrote:
> > Well, I wouldn't call Ruby a "functional" programming language in the
> > same sense as Lisp/Scheme, Haskell and Erlang define themselves as
> > functional programming languages.
> 
> Ok. I'm from an OCaml/F# background. May I just ask if anyone can translate
> the following OCaml one-liner into Ruby:
> 
>   let rec nest ?(n=2) f x = if n=0 then x else nest ~n:(n-1) f (f x)
> 
> it nests "n" applications of "f" to "x" with "n" defaulting to 2 if it isn't
> specified, e.g. "nest ~n:3 f x" gives f(f(f(x))).
The closest to the OCaml would look like:

  def nest(x, n = 2, &f)
    if n == 0 then x else nest(f[x], n - 1, &f) end
  end

nest(-3) { |a| a + 1 } #=> -1

However, I'd probably write it like:
  def nest(x, n = 2)
    (1..n).inject(x) { |acc, _| yield(acc) }
  end

nest("a", 3) { |a| a + a } #=> "aaaaaaaa"

> 
> This trivial example encapsulates much of what I love about OCaml and it
> doesn't translate well into any other language that I know.
>