1

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. 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. Is there a better way besides using the index?

3 Answers 3

7

You could use recursion like so:

f :: [a] -> [[a]]
f [] = []
f (s:ss) = ss : map (s:) (f ss)
Sign up to request clarification or add additional context in comments.

9 Comments

Right; sorry about that. However, isn't it good practice to make the base case and the general case return values of the same type? Could your answer be modified accordingly?
I'm not sure what you mean. They are of the same type; it wouldn't compile otherwise. In general [] :: [b] and in this case b ~ [a].
Jubobs: Yes, the empty list is not the same as the list containing the empty list. But they're both of the same type (otherwise you couldn't compare them for equality).
@rampion Alright. I get it now. I just learned something :)
Consider what would happen if f [] = [[]]. Then f "a" = f ('a':[]) = [] : map ('a':) (f []) = [] : map ('a':) ([[]]) = [] : ['a':[]] = [] : ["a"] = [ [], "a" ]
|
0

The Josh Kirklin's solution as a one-liner:

f = tail . foldr (\x ~(r:rs) -> (x : r) : r : map (x :) rs) [[]]

1 Comment

@Johannes Kuhn, no. This version is more readable: f = snd . foldr (\x ~(r, rs) -> (x : r, r : map (x :) rs)) ([], [])
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.