If string str1 =
"abcd", you can turn str1 to palindrome like "abcddcba".
plaindrome = str1 ++ reverse(str1) =
"abcd" ++ "dcba" = "abcddcba".
palindrome.hs
getPalindrome :: String -> String getPalindrome [] = [] getPalindrome (x:xs) = [x] ++ getPalindrome (xs) ++ [x]
*Main> :load palindrome.hs [1 of 1] Compiling Main ( palindrome.hs, interpreted ) Ok, modules loaded: Main. *Main> *Main> getPalindrome "abcd" "abcddcba" *Main> *Main> getPalindrome "a" "aa" *Main> getPalindrome "abc" "abccba" *Main> *Main> getPalindrome "mad" "maddam" *Main>
Since String is
internally implemented as list of characters, same logic is used on list of
characters also.
*Main> getPalindrome ['a', 'b', 'c'] "abccba" *Main> *Main> getPalindrome ['a', 'b', 'c', 'd'] "abcddcba" *Main> *Main> getPalindrome [] ""
No comments:
Post a Comment