是否可以制作正则表达式来确定函数的返回类型? [英] Can a regular expression be crafted which determines the return type of a function?

查看:66
本文介绍了是否可以制作正则表达式来确定函数的返回类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于以下函数的 text

function f3() {
  return Math.random() > 0.5 ? Promise.resolve(true): 'naaah'
}

是否可以编译正则表达式哪个确定 f3()调用的返回类型,而不实际调用该函数?

Can a regular expression be compiled which to determines the return type of f3() call, without actually calling the function?

推荐答案

鉴于代码,我们无法通过正则表达式确定此返回类型。矛盾证明:

Given the code, we cannot determine the return type of this via regular expressions. Proof by Contradiction:


  1. 假设我们可以使用正则表达式找到返回类型。

  1. Assume we can find the return type by using a regular expression.

返回类型在最后一行中通过对 random 的非确定性调用决定(事先不知道) )。

The return type is decided in the final line, via a non-deterministic call to random (it isn't known ahead of time).

正则表达式是确定性的 - 当在同一输入上运行时,它们总是具有相同的输出。

Regular expressions are deterministic- they always have the same output when run on the same input.

因此,函数的返回类型必须是静态的,因为我们可以运行正则表达式并找到返回类型(并且正则表达式将始终返回相同的东西)。

Thus, the function's return type must be static, since we can run a regular expression and find the return type (and that regular expression will always return the same thing).

矛盾:函数的返回类型必须是静态的,但函数的返回类型是可变的,因为 random

Contradiction: The function's return type must be static, but the function's return type is variable due to random

注意:以上假设类型必须是单一类型,并且不会自行考虑Union类型。

Note: The above assumes the type must be a single one, and does not account for Union types on its own.

此外,还有一个关于我们为什么不能这样做的证据。

Additionally, a proof on why we can't do it always.


  1. 假设在某种程度上,我们可以用某种方式计算出函数中使用的每种类型。

  1. Assume that somehow we can figure out every type used in the function in some way.

在某些时候,我们生成一个字符串 a = A+ Math.random()

At some point, we generate a string a="A"+Math.random()

稍后我们会生成一个字符串 b =class+ a +{...}

At some later point, we generate a string b="class "+a+"{...}

在此定义之后,我们执行 c = eval(new+ a +())

After this definition, we execute c= eval("new "+a+"()").

当我们返回 c ,没有正则表达式可以知道类型 - 函数中新命名的类型,随机确定,每次执行都不同。

When we return c, no regular expression can know the type- the type is newly named in the function, determined randomly and is different for every execution.

这假设问题是更一般的可以javascript正则表达式查找泛型函数的返回类型。请注意,如果有可能找到返回类型,则可以告诉该程序暂停(如果它没有停止则无法返回,如果它永远不会停止则返回类型必须是未定义的),并且暂停问题仍然没有解决。

This assumes the question was a more general "can javascript regex find the return type of a generic function." Note that if it were possible to find the return type, it would be possible to tell that the program halts (it can't return if it doesn't halt, and the return type would have to be undefined if it never halts), and the Halting problem is still unsolved.

这篇关于是否可以制作正则表达式来确定函数的返回类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆