string - Stopping condition on a recursive function - Haskell -


so, have function aims align text on left without cutting words(only white spaces). problem cannot find stopping condition of function , goes infinitely.

f n "" = ""          --weak condition f n s  = if n >= ((maximum . map length . words) s) if (s !! n == ' ' || s !! n == '\t' || s !! n == '\n')                                                      take n s ++ "\n" ++ (f n ( drop n s)) else f (n-1) s                                                      else error "try bigger width!" 

well, if n smaller longest word prompts error, else ''cuts'' string in white spaces until reaches not white space character, calls recursively n-1. use putstr avoid "\n" in output.

however, said stopping condition weak or non-existent. if there other flows in code or possible optimizations(e.g. less ifs), please tell.

your code doesn't handle case line shorter maximum length.

this obscured bug: n decremented until whitespace found, , f called recursively passing decremented value of n, limiting subsequent lines length of current line.

(also, might want drop n + 1 characters s original whitespace isn't included in output.)

you can avoid ifs using patterns:

f n "" = "" -- weak condition f n s   | n >= (maximum . map length . words) s =       if s !! n == ' ' || s !! n == '\t' || s !! n == '\n'       take n s ++ "\n" ++ f n (drop n s)       else f (n - 1) s   | otherwise = error "try bigger width!" 

Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -