views:

237

answers:

1

The python implementation

import sys

def move(src, dst, tmp, num):
    if num == 1: print 'Move from', src, 'to', dst
    else:
        move(src, tmp, dst, num-1)
        move(src, dst, tmp, 1)
        move(tmp, dst, src, num-1)

move('left', 'right', 'middle', int(sys.argv[1]))

Gives the right solution for tower of hanoi. But my scheme port,

(define move
    (lambda (src dst tmp num)
      (if (= num 1) (printf "Move from ~s to ~s \n" src dst)
          ((move src tmp dst (- num 1))
           (move src dst tmp 1)
           (move tmp dst src (- num 1))))))

Gives the right solution but in the end throws the following error.

procedure application: expected procedure, given: #<void>; arguments were: #<void> #<void>

I know that its my print statement that is throwing the error, but I can't figure out why is this happening ?

+3  A: 
 ((move src tmp dst (- num 1))
  (move src dst tmp 1)
  (move tmp dst src (- num 1)))

The above code doesn't do what you think it does :)

To execute a series of expressions / statements you need something like this:

((λ ()
  (move src tmp dst (- num 1))
  (move src dst tmp 1)
  (move tmp dst src (- num 1))))

The syntactic sugar in Scheme is

(begin
   (move ...)
   (move ...)
   (move ...)
   ...)

((move ...) (move ...) (move ...))

will be evaluated, and the code seems to work. But as soon as the recursion ends,
the interpreter will try to execute it as (op param1 param2) and there is where
you get the error #<void>; arguments were: #<void> #<void>

Nick D
The syntactic sugar is `(begin (move ...) (move ...) ...)`
Nathan Sanders
thank you Nathan.
Nick D