为什么我从 stdin 读取字符串时得到 "Prelude.read : no parse"
Why am I getting "Prelude.read : no parse" on reading a string from stdin
我 运行 遇到 forM_
循环打印结果的问题。我期待最后一个 putStrLn
函数输出结果。对于那些想要 link 问题的人 - https://www.hackerrank.com/challenges/sherlock-and-anagrams
--Returns a sublist of xs from 'from' to 'to'
slice from to xs = take (to - from + 1) (drop from xs)
--Checks if all elements in list are identical
allTheSame xs = and $ zipWith (==) xs (tail xs)
--Handles validating an anagram
checkForTwoOccurences :: [Char] -> [[Char]] -> Bool
checkForTwoOccurences occ arr
| allTheSame occ == True = False
| reverse occ == occ = False
| (occ `elemIndex` arr /= Nothing) = True
| otherwise = False
--Returns the count of anagrams that are substrings of s - n is length of s
findAnagrams s n =
let res = concat $ [ tail $ inits $ slice x (n-1) s | x <- [0..n-1] ]
in foldl (\acc x -> if (checkForTwoOccurences (reverse x) res) then (succ acc) else acc) 0 res
main :: IO ()
main = do
t_temp <- getLine
let t = read t_temp :: Int
forM_ [1..t] $ \a0 -> do
s_temp <- getLine
let s = read s_temp :: String
putStrLn $ show $ findAnagrams s $ length s
如评论所述,您不需要 "read" 您的字符串 -- 它已经是一个字符串!
所以改变
s_temp <- getLine
let s = read s_temp :: String
putStrLn $ show $ findAnagrams s $ length s
至
s <- getLine
putStrLn $ show $ findAnagrams s $ length s
应该解决该错误。
我 运行 遇到 forM_
循环打印结果的问题。我期待最后一个 putStrLn
函数输出结果。对于那些想要 link 问题的人 - https://www.hackerrank.com/challenges/sherlock-and-anagrams
--Returns a sublist of xs from 'from' to 'to'
slice from to xs = take (to - from + 1) (drop from xs)
--Checks if all elements in list are identical
allTheSame xs = and $ zipWith (==) xs (tail xs)
--Handles validating an anagram
checkForTwoOccurences :: [Char] -> [[Char]] -> Bool
checkForTwoOccurences occ arr
| allTheSame occ == True = False
| reverse occ == occ = False
| (occ `elemIndex` arr /= Nothing) = True
| otherwise = False
--Returns the count of anagrams that are substrings of s - n is length of s
findAnagrams s n =
let res = concat $ [ tail $ inits $ slice x (n-1) s | x <- [0..n-1] ]
in foldl (\acc x -> if (checkForTwoOccurences (reverse x) res) then (succ acc) else acc) 0 res
main :: IO ()
main = do
t_temp <- getLine
let t = read t_temp :: Int
forM_ [1..t] $ \a0 -> do
s_temp <- getLine
let s = read s_temp :: String
putStrLn $ show $ findAnagrams s $ length s
如评论所述,您不需要 "read" 您的字符串 -- 它已经是一个字符串!
所以改变
s_temp <- getLine
let s = read s_temp :: String
putStrLn $ show $ findAnagrams s $ length s
至
s <- getLine
putStrLn $ show $ findAnagrams s $ length s
应该解决该错误。