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']
Be the first to rate this post
- Currently 0/5 Stars.
- 1
- 2
- 3
- 4
- 5
Tags:
f#,
99 problems,
lists
Categories:
F#