0

I want to create a while loop to concatenate strings in the xs list until I find an empty string, but it seems neither we have a chance to increment an Int nor create a while loop.

So this looks like a pseudo code for Haskell, but how can I actually implement my solution?

prt :: String -> [String] -> Int -> String
prt str xs x = do
         while((xs !! (x)) /= "")
         str = str ++ (xs !! (x++))
1

1 Answer 1

7

Forget array indexes: they are often not needed. All you have to do for your task is getting the longest prefix of your list containing only non-empty strings.

takeWhile (not . null) xs
-- or
takeWhile (/= "") xs

Then you want to concatenate these strings.

concat $ takeWhile (/= "") xs

If you want to start after n strings for some reason, just drop the first n before beginning:

concat $ takeWhile (/= "") $ drop n xs

If you really want to do a custom "loop", use recursion:

g xs n = f $ drop n xs
f []      = ""
f ("":xs) = ""
f (x:xs)  = x ++ f xs
Sign up to request clarification or add additional context in comments.

4 Comments

If I understand his pseudocode correctly, he wants to do this, but starting at index x: maybe add a drop in there or something?
@MichaelRawson I added that, although I believe the string and index parameters could be added by the OP while attempting to make a loop -- it is possible that they don't really need those arguments.
Yes that is one problem I have to handle
@coderbst, note that the first expression, not . null, should generally be preferred to (/= "") because it works for types other than strings.

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.