Wednesday, January 12, 2011

Thinking in a recursive mood

A colleague issued me a lunch-time challenge today: Write a program to detect palindromes. After a few minutes of thought, I wrote a small program that used a single function to detect palindromes. It is a very functional-programming design, looking like this:

func bool IsPalindrome(s)

return true if (s.length < 2)

return IsPalindrome(s.substring(1, s.length - 1) if s[0] == s[-1]

return false

end

No looping! All objects are immutable!

What surprised me is that I thought of this solution quickly, and without thinking specifically about functional programming. It came to me, rather than me sitting down and deliberately looking for a function-programming solution.

No comments:

Post a Comment