2017-03-08 54 views
0
我无法跟踪

通过这个代码(这是正确的):跟踪ocaml的递归函数

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

::运算符不是关联的,即,(a :: b) :: ca :: (b :: c)不相同。所以你应该使用圆括号来跟踪你的子列表。

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

也许你可以把它从那里....

+0

我现在明白了,太感谢你了! – user