匿名函数的递归
我想知道...是否可以使用匿名函数进行递归?
这是一个例子:我需要获取六个字符长的字符串,该字符串可能只包含数字和空格。唯一的规则是它不能以空格开头或结尾。我们检查是否存在这种情况,如果发生这种情况 - 只需在同一个匿名函数上调用递归即可。到底如何!?
function() {
$chars = range(0, 9);
$chars[] = ' ';
length = 6;
$count = count($chars);
$string = '';
for ($i = 0; $i < $length; ++$i) {
$string .= $chars[mt_rand(0, $count - 1)];
}
$string = trim($string);
if (strlen($string) !== $length) { // There were spaces in front or end of the string. Shit!
// Do recursion.
}
return $string;
}
Possible Duplicates:
javascript: recursive anonymous function?
Anonymous recursive PHP functions
I was wondering... Is it possible to do recursion with anonymous function?
Here is one example: I need to get six-chars long string which may contain only numbers and spaces. The only rules are that it cannot start or end with spaces. We check for that and if that occurs - just call recursion on the same, anonymous, function. Just how!?
function() {
$chars = range(0, 9);
$chars[] = ' ';
length = 6;
$count = count($chars);
$string = '';
for ($i = 0; $i < $length; ++$i) {
$string .= $chars[mt_rand(0, $count - 1)];
}
$string = trim($string);
if (strlen($string) !== $length) { // There were spaces in front or end of the string. Shit!
// Do recursion.
}
return $string;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
是的,但我不会推荐它,因为它有点棘手;)
第一种可能性:
另一种:
示例取自 http://php.net/
Yes it is, but I wouldn't recommend it as it's a bit tricky ;)
First possibility:
Another one:
Examples taken from http://php.net/
答案很复杂,但并非不可能。我花了几分钟才弄清楚。我们首先必须定义一个名为 $combinator() 的实用函数。
问题的解决方案:
$combinator() 的定义:
The answer is complicated but not impossible. It took me several minutes to figure out. We first must define a utility function called $combinator().
The solution to your problem:
The definition of $combinator():
做同样事情的更明智的方法。也只需要一个循环。
不过,很抱歉回避了实际的问题。
A much saner method to do the same thing. Requires only one loop as well.
Sorry for sidestepping the actual question though.
使用 goto
但使用 goto 并不是最好的主意。
use goto
But it's not the best idea to use goto.