Search code examples
recursionsmlsmlnj

How to recursively call another function repeatedly in sml?


I have a function called mergeP:

fun mergeP(nil) = nil
| mergeP(x::[]) = x::[]
| mergeP(x::y::zs) = (x @ y)::mergeP(zs);

If mergeP is called like: mergeP([[1],[2],[3],[4]]) it will return [[1,2],[3,4]]. I want to create a function called mergeS that is recursive that repeatedly calls mergeP till the sublist equals just one list. So if mergeS were called like: mergeS([[1],[2],[3],[4]]) it would repeatedly call mergeP till it equals: [1,2,3,4]. Here is my try:

- fun mergeS(nil) = nil
= |mergeS(xs) = mergeS(mergeP(xs));

But this gives me the error:

stdIn:6.1-6.26 Warning: type vars not generalized because of
   value restriction are instantiated to dummy types (X1,X2,...)
val it = [] : ?.X1 list

Solution

  • I believe I got it to work:

    fun mergeS(nil) = nil
    | mergeS([xs]) = xs
    | mergeS(xs) = mergeS(mergeP(xs));