[英]Haskell transpose chars in String
I'm trying to write a function of the form: 我正在尝试编写以下形式的函数:
f :: String -> [String]
f st = ...
It should display all possible transposions of chars in the String. 它应该在String中显示char的所有可能的转置。 For example:
例如:
ghci> f "string"
["tsring","srting","stirng","strnig","strign"]
As you can see it should only transpose the next char with the current one. 如您所见,它只应将下一个字符与当前字符转换。 I currently have:
我目前有:
f :: String -> [String]
f [] = []
f (x:xs) = ...
but i dont know how to actually transpose the chars. 但我不知道该如何真正转换字符。
f :: String -> [String]
f (x:y:xs) = (y:x:xs) : map (x:) (f (y:xs))
f xs = []
Note, that f [x]
returns []
, but it's easy to fix, if this is desired. 注意,
f [x]
返回[]
,但是如果需要的话,很容易修复。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.