-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlongestpalindrome.hs
executable file
·54 lines (39 loc) · 1.36 KB
/
longestpalindrome.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#! /usr/bin/env nix-shell
#! nix-shell -p "haskellPackages.ghcWithPackages ( p: [p.aeson p.parsec])"
#! nix-shell -p ghcid
#! nix-shell -i runhaskell
{- problem: return the longest palindrome
-}
import System.Environment (getArgs)
import Control.Monad (forever)
isPalindrome :: String -> Bool
isPalindrome s = s == reverse s
windows :: Int -> String -> [String]
windows n s | n > length s = []
| n == length s = [s]
| otherwise = take n s : windows n (tail s)
allWindows :: String -> [String]
allWindows s = concat windowsLists where
windowsLists = map (flip windows s) (reverse [1..length s])
longestPalindrome :: String -> String
longestPalindrome = head . filter isPalindrome . allWindows
-- IO functions
runOne :: (String -> String) -> IO ()
runOne f = do
putStr "give me a string: "
str <- getLine
putStrLn $ "longest palindrome: \"" ++ f str ++ "\""
runForever :: (String -> String) -> IO ()
runForever = forever . runOne
runWithArgs :: (String -> String) -> IO ()
runWithArgs f = do
args <- getArgs
let pals = map f args
mapM_ putStrLn pals
-- runInteractive :: IO ()
runInteractive :: (String -> String) -> IO ()
runInteractive f = interact (unlines . map (show . f) . lines)
main :: IO ()
main = runInteractive longestPalindrome
-- main = runForever longestPalindrome``
-- main = runWithArgs longestPalindrome