This is not homework. I learn standard ML myself. I know a little Schema, so this question should answer in any language.
My self-imposed purpose is to write a function that builds a list of integers from 1 to n. For example, list (7) should return [1,2,3,4,5,6,7]. A solution to O (n) would be ideal.
It is easy to build the list in reverse order (ie [n, n-1, .., 1]) in linear time:
fun list 1 = 1::nil
| list n = n::list(n-1);
My attempt to build the list forward is O (n ^ 2), because the add operation is linear.
fun list 1 = 1::nil
| list n = list(n-1) @ n::nil;
My next attempt was to create a list from the end to the front (from right to left), starting from zero, tying n to the front and going back to 1. But that didn't work at all.
fun list n = (if n = 1
then 1
else list(n-1) :: n) :: nil;
- , , , , .