Welcome! Please see the About page for a little more info on how this works.

–2 votes
in Syntax and reader by

How to convert the code below to C?

one:
(defn f [x]
(cond

(>= x 0) "X é positivo"
(< x 0) "X é negativo"
))

two:
(defn f [x]
(if (== x 0)

(do (println "Zero") true)
(do (println "Outro valor") false)))

three:
(defn f

([numbers] (f 0 numbers))
([total numbers]
    (if (empty? numbers)
        total
        (f (+ (first numbers) total) (rest numbers)))))

1 Answer

+1 vote
by

I will call the C code with function names f1, f2, and f3, in the same order that your three Clojure functions were given in your question. I have not attempted to compile and run these, but they should be pretty close, since I have used C quite a bit.

char *f1 (long x)
{
    if (x >= 0) {
        return "X é positivo";
    } else if (x < 0) {
        return "X é negativo";
    }
}

One possible difference in behavior is that the returned string is ASCII encoding with default C compiler options at least, rather than Clojure's UTF-16 for Unicode. Also I am not sure whether the strings returned by f1 are mutable or not.

bool f2(long x)
{
    if (x == 0) {
        printf("Zero\n");
        return TRUE;
    } else {
        printf("Outro valor\n");
        return FALSE;
    }
}

For f3, I know that in C with a library called varargs one can write C functions that take a variable number of arguments, but it is a bit tedious to use, and I don't have it memorized precisely how. I will write a C function that always takes two arguments, and thus implements the 2-argument version of the Clojure function, but not the 1-arg version.

There are also many many slight variations on how one can represent lists of things in C, and the C code for traversing a list depends upon exactly how one represents those. I will pick one way to do it, where each element is an instance of a C struct that contains one number, and a next pointer to the next struct in the list.

typedef struct list_elem {
    long number;
    list_elem_t *next;
} list_elem_t;

long f3(long total, list_elem_t *lst)
{
    if (lst == NULL) {
        return total;
    } else {
        return f3(lst->number + total, lst->next);
    }
}
by
My friend, thanks for the reply, but the code is not compiling.
I don't know anything about the Clojure language and I have to write this code in C, if anyone else can help I appreciate it.
by
If you need to write it in C, then how well do you know C?  For example, have you written code in C that has linked lists, and traverses the linked lists?  If so, then you should be able to make small changes to the 3rd code snippet above to make it work like a C linked list.

If you have not used linked lists in C, then I would recommend learning how to do that first, which is not really a question about Clojure.
...