user3657850
user3657850

Reputation: 552

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. 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.

Upvotes: 0

Views: 170

Answers (1)

effectfully
effectfully

Reputation: 12725

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.

Upvotes: 4

Related Questions