Problem #8

"Eliminate consecutive duplicates of list elements."

My solution:

    1 #light

    2 

    3 let problem7 lister =

    4     let rec checker head tail =

    5         match tail with

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

    7                            checker h t

    8                         else

    9                            [head] @ checker h t

   10         | []        -> [head]          

   11     match lister with

   12     | h::t   -> checker h t

   13     | []    -> lister

   14 

   15 let megaList = [1;1;1;1;1;2;2;2;2;3;3;3;3;3;3;4;4;4;4;5;5;5;6;6;7;7;7

Alright. What this is going to do is take the ridiculously huge megaList and make it prettier. 

First off, the list that's passed into prob7 is matched with either 'being a list' (h::t // which is just matching the list against it's elements) OR being an empty list ([]).

If the passed-in tail (tail) is not empty, we're going to see if the head of the passed-in tail (h) is the same as the passed-in head (head).

If they're equal, we're going to run the checker with the head of the passed-in tail (h) and the tail of the passed-in tail (t) to check the next set of values. So we're just tossing out all of the values in the list that have the same value except the last one.

If they're not equal, we're appending the results of the checker function with the head of the passed-in tail (h) and the tail of the passed-in tail (t) to check the next set of values. 

And If the passed-in tail (tail) is empty ([]), we have to return the passed in head, to make sure we're getting a return value when the passed in list only contains one element. 

I'd just like to thank Jesus DeLaTorre's beautiful code that helped me ultimately understand the power of match statements for this solution and avoid some really ugly looking code. ;) 

kick it on DotNetKicks.com  


Currently rated 5.0 by 1 people

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

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

July 25. 2008 20:31