Haskell's Stream of Understanding

I am new to haskell, I tried to write a line splitting function

delim = '|' splitStr::[Char]->[[Char]]->[[Char]] splitStr list y | sL > 0 && sL < length(list) = splitStr (drop (sL+1) list) [subList]++y | otherwise = [subList]++y where subList = takeWhile (\x -> x /= delim) list sL = length(subList) split s = splitStr s [] 

However, the above code always returns the string in reverse order

 Main> split "foo|bar|java|python" ["python","java","bar","foo"] 

changing from y++[subList] to [subList]++y still gives the same result. I know there may be better ways to do this, but I want to know why this is happening.

+6
haskell
source share
2 answers
 splitStr (drop (sL+1) list) [subList]++y 

This is parsed as (splitStr (drop (sL+1) list) [subList])++y . You probably need splitStr (drop (sL+1) list) ([subList]++y) .

+5
source share

Here is what else says what sepp2k said about how to improve the code:

In your code you do not need a battery, as you can use laziness codes. I rewrote your code as I would do this:

 split :: Char -> String -> [String] split delim "" = [] split delim s = chunk : split delim rest where (chunk,_:rest) = break (==delim) s 

How it works? I split the string into the first char, which is equal to the delimiter. I return this part and call the function recursively on the rest of the list. This is very effective since Haskell will not evaluate the rest of the list until it is needed.

+5
source share

All Articles