Reverse a list

reverse([1,2,3,4]) ==> [4,3,2,1]

recursion

[1,2,3]        [reverse(L)|A]

[2,3] [1]      [reverse(L),A]

[3][2]

[ ][3]

 

Interface - user/programmer

reverse(L) = reverse(L,[]);

Auxiliary - workhorse

reverse(L,M)

"the reverse of L with M appended"

reverse([],M) Þ M;

reverse([A|L],M) Þ reverse(L, [A|M])

   

reverse([1,2,3],[4,5])

Þ reverse([2,3], [1,4,5])

Þ reverse([3], [2,1,4,5])

Þ reverse([ ], [3,2,1,4,5])

[3,2,1,4,5]

 

To Next Slide To Previous Slide To Contents