This is not homework. I'm learning Standard ML on my own. I know a bit of Scheme, too, so this question ought to be answerable in either language.
My self-imposed assignment is to write a function that constructs a list of integers from 1 to n. For example, list(7) should return [1,2,3,4,5,6,7]. An O(n) solution would be ideal.
It's easy to construct a list in reverse (i.e., [n,n-1,..,1]) in linear time:
fun list 1 = 1::nil
| list n = n::list(n-1);
My attempt to construct a list going forward is O(n^2) because the append operation is linear.
fun list 1 = 1::nil
| list n = list(n-1) @ n::nil;
My next attempt was to build a list from the end to the front (right to left) by starting with the nil, attaching n to the front, and recursing backwards to 1. But it didn't work at all.
fun list n = (if n = 1
then 1
else list(n-1) :: n) :: nil;
Something makes me think I need a helper function that builds un-terminated lists to be used in the recursion, but I'm stumped.