Home>

I manually converted a JavaScript program to C.
People can see that in C, even points to _multipleOf, so _not knows that the result of _multipleOf should be logically negated, but can it be realized by program conversion?

importPackage (java.lang)
print = function (x) {System.out.print (x + '')}
multipleOf = function (n)
{
  return function (m)
  {
    if (m% n === 0)
    {
      return true
    }
    else
    {
      return false
    }
  }
}
not = function (predicate)
{
  return function (arg)
  {
    return! predicate (arg)
  }
}
even = multipleOf (2)
odd = not (even)
print (odd (2))
print (odd (3))
# include<stdio.h>
#define FALSE 0
#define TRUE! FALSE
void print (int x) {printf ("% d", x);}
int _n;
int _multipleOf (int m)
{
  if (m% _n == 0)
  {
    return TRUE;
  }
  else
  {
    return FALSE;
  }
}
int (* multipleOf (int n)) ()
{
  _n = n;
  return _multipleOf;
}
int _not (int m)
{
return! _multipleOf (m);
}
int (* not (int (* f) ())) ()
{
  return (int (*) ()) _ not;
}
int main ()
{
  int (* even) (), (* odd) ();
  even = multipleOf (2);
  odd = not (even);
  print (odd (2));
  print (odd (3));
}
  • Answer # 1

      

    The question is whether it is possible to create a tool that performs such conversions.

    If you sayIt works with a C compiler, I think it is possible. For example, if you make JavaScript → LLVM → C language via a platform like LLVM, it will be possible to execute it with a C compiler (however, it will not be human-readable code) ).

    I think it will be difficult ifC language semanticsis achieved. Because, as I answered before, the function cannot be generated dynamically in C, so at the time ofmultipleOf (2)beforenotYou will have to provide your own framework.

    Maybe it's an idea that "it's only a constant value, so expand it", but even if you make something that can only handle constant values, it won't be in demand because it can't be used universally.

Related articles