2017-03-08 70 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