[英]Haskell delete Chars from String
I'm trying to write a function of the form 我正在尝试编写表格的功能
f :: String -> [String]
f str = ...
that returns the list of all the strings formed by removing exactly one character from str
. 该函数返回通过从
str
删除一个字符形成的所有字符串的列表。 For example: 例如:
ghci> f "stack"
["tack","sack","stck","stak","stac"]
Because String
and [Char]
are synonymous, I could use the index, but I know that you should avoid doing that in Haskell. 因为
String
和[Char]
是同义词,所以我可以使用索引,但是我知道您应该避免在Haskell中这样做。 Is there a better way besides using the index? 除了使用索引,还有更好的方法吗?
You could use recursion like so: 您可以像这样使用递归:
f :: [a] -> [[a]]
f [] = []
f (s:ss) = ss : map (s:) (f ss)
乔什·柯克林 ( Josh Kirklin )的一线解决方案:
f = tail . foldr (\x ~(r:rs) -> (x : r) : r : map (x :) rs) [[]]
Maybe a more readable way to describe it is: 也许更容易理解的描述方式是:
gaps :: [a] -> [[a]]
gaps xs = zipWith removeAt [0..] $ replicate (length xs) xs
removeAt i xs = ys ++ zs
where
(ys,_:zs) = splitAt i xs
But practically, it is slower than the other solutions. 但是实际上,它比其他解决方案要慢。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.