Search code examples
smlsmlnjml

how to stop a recursive function in this case (SML)


fun p(L) =
    [L] @ p( tl(L) @ [hd(L)] );

If L is [1,2,3] then I want to have a [ [1,2,3], [2,3,1], [3,1,2] ].

Since every time I append the first num to the end, then if L = [] then [] doesn't work here.

How to stop the function once it has the three lists?


Solution

  • You can have a parameter x in the function to keep track of how many levels deep in the recursion you are.

    fun p(L, x) =
      if x < length(L) then [L] @ p(tl(L) @ [hd(L)], x+1)
      else [];
    

    Then call the function with x=0.

    p([1, 2, 3], 0)
    

    And if you don't like the extra parameter, then as you probably know you can define another function and make it equal to the p function with the parameter forced to 0.

    fun p0(L) = p(L, 0);
    
    p0([1, 2, 3]); (* same result as p([1, 2, 3], 0); *)