Hi all im new to programming and im doing a problem for learning and enjoyment. Im a bit stuck at this point.. The problem is from Introduction to Programming using Sml 5.9
I want to split a list of [x1, x2, x3, ... ,xn] = ([x1, x3,....], [x2, x4,...])
This is what I have made so far:
fun split [] = []
| split (x1::x2::x3::x4::xs) = ([x1, x3], [x2, x4])::split xs
val test1split = split [1, 1, 2, 3];
From this I get:
[([1, 2], [1, 3])]…. (I want a tuple with splitting list and not this obviously)
If there are more than 4 elements then the function doesn’t work. Maybe I need a helper function to sort even and odd elements in a list first? I hope someone can help me with tracking my mind in the correct direction, until then I keep trying.
I’ll try not to give too much away, but here are some tips:
[], one for[x].splitreturning a list, rather than a tuple. The result of your first base case should be([],[]).split xswill return a tuple(ys,zs). You need to extract these values, and build the resulting tuple in terms ofys,zs,x1andx2.(Edit) A couple of points on your revised solution:
split x1::x2::xssplit [x,y]is handled by the general case – no need for another base case.xsdirectly into both halves of your output – you need to split it first. Start withlet (ys, zs) = split xs in ...