如何用Haskell实现回文字符串的前半部分提取函数?
实现halfPalindrome函数提取回文的前半部分
需求:编写halfPalindrome函数,判断输入字符串是否为回文:若是,用Just返回其前半部分;若不是,则返回Nothing。
示例:
halfPalindrome "boy"→NothinghalfPalindrome "abba"→Just "ab"
最初尝试的代码(存在问题)
halfPalindrome :: String -> Maybe String halfPalindrome x = if x == reverse x then Just half else Nothing half :: [a] -> ([a], [a]) half xs = (take 1 xs, drop 1 xs) where 1 = div (length xs) 2
修正后的可行代码
完整版本
halfPalindrome :: String -> Maybe String halfPalindrome x | x == reverse x = let (a, _) = half x in Just a | otherwise = Nothing first_half :: [a] -> [a] first_half = (\xs -> case xs of [] -> [] xs -> take ((length xs) `div` 2 ) xs) second_half :: [a] -> [a] second_half = (\xs -> case xs of [] -> [] xs -> drop ((length xs) `div` 2 ) xs) half :: [a] -> ([a],[a]) half = (\xs -> case xs of [] -> ([],[]) xs -> (first_half xs, second_half xs))
简化版本
halfPalindrome :: String -> Maybe String halfPalindrome x | x == reverse x = let (a, _) = half x in Just a | otherwise = Nothing half :: [a] -> ([a], [a]) half xs = ((take s xs), (drop s xs)) where s = (length xs ) `div` 2
内容的提问来源于stack exchange,提问作者ipholie46
相关产品推荐
相关产品推荐

