1

我是一个初学者 OCaml 程序员,试图在 OCaml 中创建一个函数来解决河内塔问题,该解决方案由一个移动列表表示,其中“移动”存储在表单的元组中(startPeg,endPeg)。

这是我到目前为止所拥有的:

type peg = A | B | C
type move = peg * peg


let towers (m : int) : (move list) =
  let rec solve n a b c = match n with
  |0 -> []
  |_ -> (solve (n-1) a c b) :: (a,b) :: (solve (n-1) c b a) in
  solve m A B C 

我收到错误消息:

文件“induction.ml”,第 8 行,字符 8-27:错误:此表达式的类型为 'a 列表,但表达式应为 'a 类型。类型变量 'a 出现在 'a 列表中

并且不知道如何解决它。谁能帮我纠正我的错误?谢谢

4

1 回答 1

7

The operator :: adds an element to the head of a list. You're using it to concatenate lists. Your code will compile if you change the first :: to the list concatenation operator @.

type peg = A | B | C
type move = peg * peg


let towers (m : int) : (move list) =
  let rec solve n a b c = match n with
  |0 -> []
  |_ -> (solve (n-1) a c b) @ (a,b) :: (solve (n-1) c b a) in
  solve m A B C 

I don't know whether the resulting code is correct, but I hope this gets you going again.

于 2013-10-05T22:36:31.227 回答