codelife
codelife

Reputation: 17

While loop in Haskell

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++))

Upvotes: 0

Views: 1089

Answers (1)

chi
chi

Reputation: 116139

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

Upvotes: 7

Related Questions