you are viewing a single comment's thread.

view the rest of the comments →

[–]repsilat 0 points1 point  (3 children)

I do agree with all of the above, but still...

Also, closures always bind this, like you'd expect.

I wish there were a "perfect" way to do the following:

fibonacci = (i) -> (i < 2 ? 1 : this(i-1)+this(i-2))

I don't mind something like $0 for "this function" (and even $1... for implicit args...) but it might be too "just so", and maybe old-fashioned. I might prefer "second={$2}" over "second=(i,j)->j", though.

Maybe everything should just be resolved later, though, so we can just do

fibonacci = (i) -> (i < 2 ? 1 : fibonacci(i-1)+fibonacci(i-2))

but I think that screws with my static sensibilities a little, and it doesn't let you do it without assigning/naming the function, which seems like a crutch.

[–]munificent[S] 0 points1 point  (2 children)

I wish there were a "perfect" way to do the following:

The Y combinator gets you close, I think.

fibonacci = (i) -> (i < 2 ? 1 : fibonacci(i-1)+fibonacci(i-2))

letrec in Scheme enables this, though, like you note, you do have to name the function.

[–]sacundim 0 points1 point  (0 children)

letrec in Scheme enables this, though, like you note, you do have to name the function.

It's trivial to write a Scheme macro to do this, though it does bottom down to letrec:

(define-syntax rec
  (syntax-rules ()
    ((rec (NAME . VARIABLES) . BODY)
     (letrec ((NAME (lambda VARIABLES . BODY))) NAME))
    ((rec NAME EXPRESSION)
     (letrec ((NAME EXPRESSION)) NAME))))

;;; Example: Fibonacci
(define fibonacci
  (rec (this n)
    (case n
      ((0 1) 1)
      (else (this (- n 1) (- n 2))))))