我(相信)以下函数定义是尾递归的:
fun is_sorted [] = true
| is_sorted [x] = true
| is_sorted (x::(y::xs)) =
if x > y
then false
else is_sorted (y::xs)
Run Code Online (Sandbox Code Playgroud)
琐碎的是,它等同于以下声明
fun is_sorted [] = true
| is_sorted [x] = true
| is_sorted (x::(y::xs)) =
(x <= y) andalso (is_sorted (y::xs))
Run Code Online (Sandbox Code Playgroud)
然而在这个版本中,最后一步是应用'andalso',所以它不是尾递归的.或者它似乎是这样,除了因为(至少是标准的)ML(NJ)使用短路评估,并且实际上/不是/最后一步.那么这个函数会有尾调用优化吗?还是有任何其他有趣的实例,其中明显使用尾递归的ML函数实际上得到优化?
我正在编写一个简单的Knight's Tour程序,带有图形显示.我已经编写了它来使用控制台,现在我正在尝试将代码转移到它以便它可以与swing一起使用.我有一个按钮,其动作监听器启动并运行该过程.这是代码:
askButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int[][] tour = getBoard(); // generates a matrix representing a successful knight's tour
int count = 0;
while (count < 64) {
count++;
Location loc = searchFor(count, tour); //gets the location of the int "count" inside the matrix "tour"
board.setVisible(false); //board contains a matrix of JPanels called "grid".
grid[loc.row()][loc.column()].add(new JLabel("" + count)); //adds JLabel to JPanel with the proper number
board.setVisible(true); //reset to visible to show changes
delay(1000); //wait 1000 …Run Code Online (Sandbox Code Playgroud) 我的目标是写一个基本的国际象棋玩AI.它并不需要令人难以置信,但我希望它能够对某些熟悉游戏的人有一定程度的能力.
我有一个名为Piece的特征,它有抽象方法canMakeMove(m:Move,b:Board)和allMovesFrom(p:Position,b:Board).出于显而易见的原因,这些方法对于程序逻辑很重要,并且由具体类King,Queen,Pawn,Rook,Bishop和Knight实现.因此在其他地方,例如在确定特定板是否具有King的代码中,这些方法在类型为抽象类型Piece的值上调用,(piece canMakeMove(...,... ))所以调用的实际方法是在运行时通过动态调度确定的.
我想知道这对于国际象棋AI程序来说是否太昂贵了,而这个程序将不得不多次执行此代码.在网上浏览并阅读有关国际象棋编程的更多内容之后,我发现国际象棋棋盘的最常见表现形式不像我的Vector [Vector [Option [Piece]],而是一个可能使用的int矩阵('bit board')关于板上值的switch语句,以实现我目前依靠动态调度来实现的效果.这会阻止我的AI达到可行的性能水平吗?