2

I want to use Haskell to format Text with giving Strings and length of the line. But keep getting a same unknown error at "chunks" function for no reason!! Here is the code:

module Format where
data Format = Flushleft | Justify | Flushright

-- Help-function for chunks
oneChunk :: [String] -> [[String]]
oneChunk [] = [[]]
oneChunk (s:ls) = [words s] ++ oneChunk ls

chunks :: Int-> [String]-> [[String]]
chunks i s = chunk' i (oneChunk s) where
         chunk' i [[]] = [[]]
         chunk' i (fi:se:ls)
         | (length fi) + (length se) < i = [fi ++ se] 
                                            ++ chunk' i (se:ls)
         | otherwise = [fi] ++ [se] ++ chunk' i (se:ls)

Here is the error message:

Format.hs:13:14: error:
parse error (possibly incorrect indentation or mismatched brackets)
|
13 |              | (length fi) + (length se) < i = [fi ++ se] ++ 
chunk' i (se:ls)
|  

1 Answer 1

4

As it is stated in the error message the indentation is not correct. You need pattern guards to be indented relative to function declaration (see Control structures).

So your code should be like this:

chunks :: Int-> [String]-> [[String]]
chunks i s = chunk' i (oneChunk s) where
    chunk' i [[]] = [[]]
    chunk' i (fi:se:ls)
         | (length fi) + (length se) < i = [fi ++ se] 
                                            ++ chunk' i (se:ls)
         | otherwise = [fi] ++ [se] ++ chunk' i (se:ls)

I don't understand what problem you are trying to solve but seems like you can simplify your code a bit.

oneChunk applies words to each element of its argument and adds [] to the end. This can be stated as (read a bit on maps and pointfree style for more info).

oneChunk = (++[]) . map words

chunk' uses variable i from chunks so you can just drop it. Also some parentheses are unneeded and you can replace [x] ++ y with x:y):

chunks :: Int-> [String]-> [[String]]
chunks i = chunk' . map words where
    chunk' [] = []
    chunk' (fi:se:ls)
         | length fi + length se < i = (fi ++ se) : chunk' (se:ls)
         | otherwise = fi : se : chunk' (se:ls)
Sign up to request clarification or add additional context in comments.

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.