开发者

Advice on translating code from very unrelated languages (in this case Scheme to Python)?

Reasoning: I'm trying to convert a large library from 开发者_如何学CScheme to Python

Are there any good strategies for doing this kind of conversion? Specifically cross-paradigm in this case since Python is more OO and Scheme is Functional.

Totally subjective so I'm making it community wiki


I would treat the original language implementation almost like a requirements specification, and write up a design based on it (most importantly including detailed interface definitions, both for the external interfaces and for those between modules within the library). Then I would implement from that design.

What I would most definitely NOT do is any kind of function-by-function translation.


Use the scheme implementation as a way of generating test cases. I'd write a function that can call scheme code, and read the output, converting it back into python.

That way, you can write test cases that look like this:

def test_f():
  assert_equal(library.f(42), reference_implementation('(f 42)'))

This doesn't help you translate the library, but it will give you pretty good confidence that what you have gives the right results.

Of course, depending on what the scheme does, it may not be quite as simple as this...


I would setup a bunch of whiteboards and write out the algorithms from the Scheme code. Then I would implement the algorithms in Python. Then, as @PaulHankin suggests, use the Scheme code as a way to write test cases to test the Python code


If you don't have time to do as the others have suggested and actually re-implement the functionality, there is no reason you CAN'T implement it in a strictly functional fashion.

Python supports the key features necessary to do functional programming, and you might find that your time was better spent doing other things, especially if absolute optimization is not required. On the other hand, you might find bug-hunting to be quite hard.


Write a Python interpreter in Scheme and directly translate your program to that :-) You can start with def:

 (define-syntax def
      (syntax-rules ()
        ((def func-name rest ...)
         (define func-name (lambda rest ...)))))

 ;; test

 (def sqr (x) (* x x))
 (sqr 2) => 4
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜