cschemer6rs

Scheme to C translator


I tried to generate C code starting from a scheme function and I do not manage to find any translator from scheme to C. I tried to convert this function to C.

(define f
  (lambda(n)
     (if (= n 0) 1
         (* n (f (- n 1))))))

(display (f 10))
(newline)

I tried to use gambit (gsc) and it generates a C file that looks merely like a file to load in some interpreter, not a file containing a main function that can be executed.

Is there some application that generates C code that can be directly executed? The functions from standard scheme library like display should be linked with some object file.

EDIT:

My purpose is to understand the algorithms used by professional translators.


Solution

  • There are many such translators, dating back at least to the 1980s I think CHICKEN is a good current one.

    If you want to use that:

    1. get CHICKEN;
    2. build & install it with the appropriate make incantation (this was painless for me on OSX, it should be very painless indeed on Linux therefore, although it may be harder on Windows);
    3. stash your code in a file I'll call f.scm.
    4. if you want to see the C code, compile with chicken f.scm which will produce a few hundred lines of incomprehensible C;
    5. if you want just the executable, use csc to create it.

    There is an extensive manual which you will need to read if you want to do anything nontrivial, such as linking in C libraries or talking to Scheme code from C.


    Without knowing what you are after, this smells as if it may be an XY problem. In particular:

    There are many examples of each of these. Some of these systems may also compile to, or via, C, but one does not depend on the other.

    Finally, if you want to understand how Scheme compilers which target C work (or how Scheme compilers which target any language, including assembler), then the traditional approach probably still works best: find a well-written one for which source is available, and read & tinker with its source code.