我有这个函数来检查一个字符是否是这些标点符号之一。
checkpunctuation:: Char -> Bool
checkpunctuationc = c `elem` ['.', ',', '?', '!', ':', ';', '(', ')']
我必须编写另一个函数,在每个标点符号后添加一个空格
format :: String -> String
我知道如何在给定数量的字符之后添加空格,但不知道如何在特定字符后添加。
答案 0 :(得分:2)
简单的递归选项:
format :: String -> String
format [] = []
format (x:xs) | checkpuntuationc x = x : ' ' : format xs
| otherwise = x : format xs
答案 1 :(得分:2)
这可能是一种更优雅的方式,但是
format :: String -> String
format s = concat [if (checkpunctuation c) then (c:" ") else [c] | c <- s]
会工作(谢谢,@ Sheri Ya!)。
根据评论进行修改
要计算格式化后标点字符的总长度,您可以使用
sumLength :: [String] -> Int
sumLength strings = 2 * (sum $ fmap length (fmap (filter checkpunctuation) strings))
因为它是标点字符数总和的两倍。
答案 2 :(得分:2)
另一种选择是foldr
使用helper
函数:
helper :: Char -> String -> String
helper x xs | checkpunctuation x = x : ' ' : xs
| otherwise = x : xs
帮助程序检查第一个字符是否为标点符号。如果是这样,它会插入一个空格,否则就不会。
然后将format
定义为:
format :: String -> String
format = foldr helper []
示例电话:
*Main> format "Hello? Goodbye! You say goodbye!! (and I say Hello)"
"Hello? Goodbye! You say goodbye! ! ( and I say Hello) "
此功能也适用于&#34; 无限字符串&#34;:
*Main> take 50 $ format $ cycle "Hello?Goodbye!"
"Hello? Goodbye! Hello? Goodbye! Hello? Goodbye! He"
因此,虽然我们为它提供了一个保持cycle
的字符串,因而永远不会结束,但我们可以得到结果的前50个字符。