I am new to SML and was a bit confused. I am trying to write a function called makeList of type int -> int list that takes as input a positive integer n and returns the list [1, 2, ..., n]
I want the only input to be the ending number, but I am struggling on doing this without specifying a starting point as well.
fun createList(start:int, ending:int) =
if(start = ending)
then []
else
start::createList(start 1, ending);
I want to be able to input just one number, such as 6 and get a list such as: [1,2,3,4,5,6] and I want to do this without using an external library like list.something
This is the only way I was taught, and I would appreciate tips on how to improve.
CodePudding user response:
You're 99% of the way there. With your current function, createList(1, 7) yields [1, 2, 3, 4, 5, 6]. You just need another function that automatically fills in one of the parameters.
fun createList(start, ending) =
if start = ending then []
else start :: createList(start 1, ending);
fun createList'(ending) =
createList(1, ending 1);
Try this and createList'(6) will yield [1, 2, 3, 4, 5, 6].
Now, let's say you don't want both to be visible. You can "hide" one function as a local binding.
fun createList(ending) =
let
fun aux(start, ending) =
if start = ending then []
else start :: aux(start 1, ending)
in
aux(1, ending 1)
end;
