Problem #6

Now we're going to work on something that is (just slightly) more challenging than what we've encountered so far.

"Find out whether a list is a palindrome."

Sounds easy enough. First off we're going to create a simple method to compare two lists and print if they are equals or not. We would never really do something like this but for the sake of example it works out.

let printListsEqual (listy : List<char>) =

     if listy.Equals(List.rev listy) then

          printfn "It's a palindrome!"

     else

          printfn "Not a palindrome!"

Notice that we're actually defining the parameters as a list of characters (using generics) instead of using the type inference of the F# compiler. We would get a compile error if we did not infer the type and tried to use the equals method.

Next we're going to create two lists. We want the first one to be a palindrome -- where the second is just to prove that our function is working.

let listForward = ['r'; 'a'; 'c'; 'e'; 'c'; 'a'; 'r']

let listGarbage = ['g'; 'a'; 'r'; 'b'; 'a'; 'g'; 'e']

Finally, we're going to run the palindrome thru the function we created above with the reverse of itself as the second parameter... then we're going to run the same method except instead of the reversed list we're going to pass in the garbage list.

printListsEqual listForward

print_newline()

printListsEqual listGarbage

 The results are just as intended -- the result of running the function the first time is 'It's a palindrome', while the second is 'Not a palindrome!' Sweet we're finally on to some slightly more complicated code! The full code is listed below:

    1 #light

    2 

    3 let printListsEqual (listy : List<char>) =

    4      if listy.Equals(List.rev listy) then

    5           printfn "It's a palindrome!"

    6      else

    7           printfn "Not a palindrome!"

    8 

    9 

   10 let listForward = ['r'; 'a'; 'c'; 'e'; 'c'; 'a'; 'r']

   11 let listGarbage = ['g'; 'a'; 'r'; 'b'; 'a'; 'g'; 'e']

  kick it on DotNetKicks.com


Be the first to rate this post

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

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

Related posts

Comments

March 11. 2008 02:01

Jesus DeLaTorre

Hey ryan, this is what I came up with.

let is_palindrome (listy : List<char>) =
let rec is_palindrome_rec (list : List<char>) low high =
if (low < high) then
if (List.nth list low) = (List.nth list high) then
is_palindrome_rec list (low + 1) (high - 1)
else
false
else true
in is_palindrome_rec listy 0 (List.length listy - 1)

Jesus DeLaTorre

Add comment


(Will show your Gravatar icon)  

  Country flag

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



Live preview

July 4. 2009 06:04