跟踪Ocaml递归函数

时间:2017-03-08 01:45:44

标签: recursion ocaml tracing

我无法跟踪此代码(这是正确的):

    let rec prepend (l: int list list) (x: int) : int list list = 
        begin match l with
          | [] -> []
          | hd :: tl -> (x :: hd) :: (prepend tl x)
        end

prepend [[]; [2]; [2;3]] 1 = [[1]; [1;2]; [1;2;3]]

我的追踪不正确,但我不确定错误:

prepend ([]::2::[]::2::3::[]::[]) 1 =
1::[]::prepend (2::[]::2::3::[]::[]) 1 =
1::[]::1::2::prepend([]::2::3::[]::[]) 1 =
1::[]::1::2::1::[]::prepend(2::3::[]::[]) 1 --> 
This is incorrect because then it comes out as [1] ; [1;2;1]
when it should be [1]; [1;2] ; [1;2;3]

1 个答案:

答案 0 :(得分:1)

::运算符不具有关联性,即(a :: b) :: ca :: (b :: c)不同。因此,您应该使用括号来跟踪您的子列表。

prepend ([] :: (2 :: []) :: (2 :: 3 :: []) :: []) 1 =>
(1 :: []) :: prepend ((2 :: []) :: (2 :: 3 :: []) :: []) 1 => 
(1 :: []) :: (1 :: 2 :: []) :: prepend ((2 :: 3 :: []) :: []) 1 => ...

也许你可以从那里拿走它......