You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Haskell实现回文字符串的前半部分提取函数?

实现halfPalindrome函数提取回文的前半部分

需求:编写halfPalindrome函数,判断输入字符串是否为回文:若是,用Just返回其前半部分;若不是,则返回Nothing。

示例:

  • halfPalindrome "boy" → Nothing
  • halfPalindrome "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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 17:09:32