I want to split a list into a tupple of odd and even elements

a 夏天 提交于 2019-12-10 21:57:51

问题


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.


回答1:


I'll try not to give too much away, but here are some tips:

  • You need two base cases - one for [], one for [x].
  • Your general case only needs to deal with two elements, not four (putting one in the first list, and one in the second)
  • At the moment, you've got split returning a list, rather than a tuple. The result of your first base case should be ([],[]).
  • In the general case, the recursive split xs will return a tuple (ys,zs). You need to extract these values, and build the resulting tuple in terms of ys, zs, x1 and x2.

(Edit) A couple of points on your revised solution:

  • You only need to deal with two elements at a time - the general case should be split x1::x2::xs
  • split [x,y] is handled by the general case - no need for another base case.
  • You're missing the recursive call! Elements are ending up in both lists because you're putting xs directly into both halves of your output - you need to split it first. Start with
    let (ys, zs) = split xs in ...



回答2:


fun split [] = ([], [])   
  | split [x] = ([x], [])  
  | split (x1::x2::xs) = 
               let 
                 val (ys, zs) = split xs
               in 
                ((x1::ys), (x2::zs))
              end;



val test1split = split [1, 1, 2, 3, 5, 6] = ([1, 2, 5], [1, 3, 6])
val test2split = split [8, 7, 6, 5, 4, 3] = ([8, 6, 4], [7, 5, 3])
val test3split = split [8, 7] = ([8], [7])
val test4split = split [8] = ([8], [])

Solved it... Not completely sure how lol, need alot more practice to master it. Couldn't have done it without the pointers... Thx alot for the help Nick Barnes.



来源:https://stackoverflow.com/questions/12868924/i-want-to-split-a-list-into-a-tupple-of-odd-and-even-elements

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!