Longest Palindromic Substring in Haskell

Published on 11 May 2026 (Updated: 11 May 2026)

Welcome to the Longest Palindromic Substring in Haskell page! Here, you'll find the source code for this program as well as a description of how the program works.

Current Solution

module Main where

import System.Environment
import Data.List (maximumBy, tails, inits)
import Data.Maybe (listToMaybe)
import Data.Function ((&))
import Data.Ord (comparing)

substrings :: [a] -> [[a]]
substrings = concatMap tails . inits

longestPalindromicSubstring :: String -> Maybe String
longestPalindromicSubstring str =
  case palindromes of
    [] -> Nothing
    _  -> Just $ maximumBy (comparing length) palindromes
  where palindromes = substrings str & filter (\s -> length s > 1 && reverse s == s)

main :: IO ()
main = do
  args <- getArgs
  case listToMaybe args >>= longestPalindromicSubstring of
    Nothing  -> putStrLn "Usage: please provide a string that contains at least one palindrome"
    Just res -> putStrLn res

Longest Palindromic Substring in Haskell was written by:

If you see anything you'd like to change or update, please consider contributing.

How to Implement the Solution

No 'How to Implement the Solution' section available. Please consider contributing.

How to Run the Solution

No 'How to Run the Solution' section available. Please consider contributing.