我想要一个函数,用字母表中的每个其他字母替换字符串中的字母。 示例:
f :: String -> [String]
f = ...
ghci> f "foo"
["aoo","boo,"coo","doo","eoo","goo","hoo"..."fao",fbo","fco","fdo",...."foa","fob","foc","fod"...]
我目前得到了:
alphabet :: [Char]
alphabet = ['a'..'z']
replaced1 :: String -> [String]
replaced1 [] = []
replaced1 (x:xs) = (alphabet++xs) : map (x:) (replaced1 xs)
当然这不起作用,因为它增加了整个字母,但我不知道如何从字母表中只拿一个字符。 我希望你能帮助我。
答案 0 :(得分:3)
假设您的函数的参数与模式(x:xs)
匹配;为了简洁起见,我不会讨论基本案例。
使用列表推导生成一个字符串列表,其中x
被字母表中的所有其他字母替换:
[ c:xs | c <- alphabet, c /= x ]
生成器从字母表中抽取字符c
,但谓词禁止c
与x
相同。
递归地将函数应用于String参数xs
的尾部:
f xs
将字符x
添加到2中获得的字符串列表中的每个字符串。
map (x:) (f xs)
将结果3.附加到1。:
[ c:xs | c <- alphabet, c /= x ] ++ map (x:) (f xs)
全部放在一起:
alphabet :: String
alphabet = ['a'..'z']
f :: String -> [String]
f [] = []
f (x:xs) = [ c:xs | c <- alphabet, c /= x ] ++ map (x:) (f xs)
测试:
ghci> f "foo"
["aoo","boo","coo","doo","eoo","goo","hoo","ioo","joo","koo","loo","moo","noo",
"ooo","poo","qoo","roo","soo","too","uoo","voo","woo","xoo","yoo","zoo","fao",
"fbo","fco","fdo","feo","ffo","fgo","fho","fio","fjo","fko","flo","fmo","fno",
"fpo","fqo","fro","fso","fto","fuo","fvo","fwo","fxo","fyo","fzo","foa","fob",
"foc","fod","foe","fof","fog","foh","foi","foj","fok","fol","fom","fon","fop",
"foq","for","fos","fot","fou","fov","fow","fox","foy","foz"]