Problem #9

"Pack consecutive duplicates of list elements into sublists."

My solution:

    1 #light

    2 

    3 let oSnap = [1;1;1;2;2;2;2;2;2;3;3;3;3;3;3;4;]

    4 

    5 let prob9 listegosaurus =

    6     let rec packer listy tempy head tail =   

    7         match tail with

    8         | h::t -> if head = h then

    9                     packer listy (tempy @ [head]) h t

   10                   else

   11                     packer (listy @ [tempy @ [head]] ) [] h t

   12         | []   -> listy @ [[head]]

   13 

   14     match listegosaurus with

   15     | h::t   -> packer [] [] h t

   16     | []    -> [listegosaurus]

 This one was a wee bit tougher than problem 8. The general layout isn't all too different from problem 8, but inside of packer is where things are actually happening, so I'll head over there.

When the packer function is first called, I tossed in two empty lists for listy and tempy, along with the head and tail of listegasaurus. I had to make these two lists because there was really no other way (that I could think of) for me to hang on to elements that were the same while still holding on to the final list. 

Once inside packer, we just have to pack like elements into a list separated from different elements. To do this, I made it so if the tail passed in isn't empty (noting that we're at the last element) we just have to figure out if the head we passed in is the same as the next value in the list (the head from the tail we passed in). If so, we're just going to append that element as a list (noted by being inside of [ ]'s) to tempy and go through packer again with the next value and the rest of the tail. 

When the values are finally different, we just append tempy as a list (with head appended, so we don't lose a value) to our final list, listy.

That's pretty much it. Again, if anyone else has other ways of doing this, feel free to post in the comments. 


Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Tags:
Categories:

0 Comments
Actions: E-mail | Permalink | Comment RSSRSS comment feed

Related posts

Add comment


(Will show your Gravatar icon)  

  Country flag

[b][/b] - [i][/i] - [u][/u]- [quote][/quote]



Live preview

August 28. 2008 14:14