-7

我正在开发一个源到源编译器,旨在在不同的编程语言之间翻译程序。现在,我正在尝试找到一种方法来跟踪不同编程语言中的等效函数,以便找出一种语言中的哪个函数与另一种语言中的相同函数等效。

给定一个像这样的数组,是否可以编写一个函数来返回另一种语言的相应函数(例如,使用诸如 之类的查询print(getCorrespondingValue("Python", [["Java", "System.out.println"]])),它将返回 Python 中对应System.out.println于 Java 中的函数)?

correspondingFunctionDatabase = [
    [
        ["Java", "System.out.println"], ["JavaScript", "console.log"], ["Python", "print"],
    ],
    [
        ["Java", "s1.replaceAll(str1, str2);"], ["JavaScript", "str.replace(str1, str2)"], ["Python", "str.replace(str1, str2)"], ["Haxe", "replace(str, str1, str2)"]
    ],
    [
        ["JavaScript", "str.split(separator)"], ["Java", "str.split(separator)"], ["Python", "re.split(separator, string)"]
    ],
    [
        ["JavaScript", "eval(statement)"], ["Python", "eval(statement)"] 
    ]
]
4

5 回答 5

10

首先建立一个查找,然后访问它:

from itertools import permutations
from collections import defaultdict

dd = defaultdict(dict)
for row in correspondingFunctionDatabase:
    for fst, snd in permutations(row, 2):
        dd[tuple(fst)][snd[0]] = snd[1]

print dd['Java', 'System.out.println']['Python']
# print
print dd['JavaScript', 'eval(statement)']['Python']
# eval(statement)
print dd['JavaScript', 'eval(statement)'].get('FakeLanguage', 'No Matching Function')
# No Matching Function

请注意,这也意味着您可以获得语句可以翻译成的语言,例如:

print list(dd["Java", "s1.replaceAll(str1, str2);"])
# ['Python', 'Haxe', 'JavaScript']
于 2013-07-15T23:25:30.233 回答
5

根据评论中的要求,这可能是我通常会如何实现这一点。实际上,我会使用 Mongo 数据库,但为了简洁起见。

DB = [
{"Java": "System.out.println", "JavaScript": "console.log", "Python", "print"},
{"Java": "s1.replaceAll(str1, str2);", "JavaScript": "str.replace(str1, str2)", "Python": "str.replace(str1, str2)", "Haxe": "replace(str, str1, str2)"},
{"JavaScript": "str.split(separator)", "Java": "str.split(separator)", "Python": "re.split(separator, string)"}
{"JavaScript": "eval(statement)", "Python": "eval(statement)"}]

def get_corresponding_value(language, entry):
    try:
        index = [value for key,value in DB if key == entry[0]].index(entry[1])
        return DB[index].get(language, "No equivalent found")
    except ValueError:
        print "Could not find function: %s " % entry[1]
        raise

或恋物癖者的单线:

get_equiv = lambda language,entry: DB[[value for key,value in DB if key==entry[0]].index(entry[1])][language]

我知道 try except 有点过分,但未处理的错误是我的一个小烦恼。

于 2013-07-15T23:26:31.840 回答
0

我认为有一种更简单的解决方案:

# Build a list of dicts. Each dict maps language names
# to function names.
cfDicts = [dict(x) for x in correspondingFunctionDatabase]

def getCorrespondingValue(lang, construct):
    # Select all dicts that have an entry for lang and for
    # the given construct. A construct is a tuple of the
    # form (language, function).
    ds = [d for d in cfDicts if lang in d and
                                construct[0] in d and
                                d[construct[0]] == construct[1]]
    if len(ds) == 0:
        # There is no equivalent for `lang` to `construct`.
        return None
    else:
        # There should be only one match.
        assert len(ds) == 1, 'Multiple entries for' + str(construct)
        # Return the first match.
        return ds[0][lang]

请注意,我已将第二个参数更改为仅包含一个构造。修改它以接受多个构造很容易(而且毫无意义)。

例子:

In [117]: getCorrespondingValue("Python", ["Java", "System.out.println"])
print
于 2013-07-15T23:26:56.130 回答
0

你在这里,使用两个字典:

equivalenceclasses = {n: dict(map(tuple,klass)) for n,klass in enumerate(correspondingFunctionDatabase)}
bypair = {tuple(pair):n for n,klass in enumerate(correspondingFunctionDatabase) for pair in klass}

#note pep8 style name
def get_corresponding_function(targetlang, pair):
    # you could catch exceptions here
    return equivalenceclasses.get(bypair.get(tuple(pair))).get(targetlang)

print get_corresponding_function("Python", ["Java", "System.out.println"])

“数据库”中的每一行代表一个类;每个这样的类都可以由一个整数标识,并且该整数可用于连接两个字典。当然,您可以只使用sqlite(或其他 sql)或自由格式数据库。

在此处查看实际操作:http: //ideone.com/oxrdEV

于 2013-07-16T00:10:00.357 回答
-4

是的,绝对有可能做到这一点。我已经用 Python 编写了一个完整的工作解决方案。

首先,我用不同的编程语言创建了一组对应的函数:

correspondingFunctionDatabase = [
    [
        ["Java", "System.out.println"], ["JavaScript", "console.log"], ["Python", "print"],
    ],
    [
        ["Java", "s1.replaceAll(str1, str2);"], ["JavaScript", "str.replace(str1, str2)"], ["Python", "str.replace(str1, str2)"], ["Haxe", "replace(str, str1, str2)"]
    ],
    [
        ["JavaScript", "str.split(separator)"], ["Java", "str.split(separator)"], ["Python", "re.split(separator, string)"]
    ],
    [
        ["JavaScript", "eval(statement)"], ["Python", "eval(statement)"] 
    ]
]

接下来,我编写了一个名为 的函数getCorrespondingValue,它将返回一种语言的函数,该函数对应于另一种语言的函数:

def containsAll(containingArray, containsAllOfThese):
    i = 0
    while(i < len(containsAllOfThese)):
        if((containsAllOfThese[i] in containingArray) == False):
            return False
        i += 1
    return True

def getCorrespondingValue(valueToRetrieve, valueCorrespondsTo, mainArray=correspondingFunctionDatabase, printMessages=False):
    i = 0
    correspondingValues = []
    while(i < len(mainArray)):
        if(containsAll(containsAllOfThese=valueCorrespondsTo, containingArray = mainArray[i])):
            if(printMessages == True):
                print("The elements of the array:\n", valueCorrespondsTo)
                print("Are contained in the array:\n", str(mainArray[i])+"\n")
            j = 0
            while(j < len(mainArray[i])):
                if(mainArray[i][j][0] == valueToRetrieve):

                    print(mainArray[i][j])

                    correspondingValues += [mainArray[i][j][1]]
                j += 1
        i += 1
    print("The retrieved values for", valueToRetrieve, "from", valueCorrespondsTo, "are", correspondingValues)
    return correspondingValues

以下是使用此功能的几个示例:

'''
This function call returns the Python function that corresponds to System.out.println in Java.
'''
print(getCorrespondingValue("Python", [["Java", "System.out.println"]]))

'''
This function call returns the Java function that corresponds to console.log in JavaScript.
'''
print(getCorrespondingValue("Java", [["JavaScript", "console.log"]]))
于 2013-07-15T22:33:47.380 回答