string - Decremented value called in the recursion in Haskell -


so, have function aligns text left given column width. have fixed of problems, unable make not use decremented parameter once called, return starting value of n. here code:

 f n s    | length s <= n = take (length s) s ++ "\n"                        | n >= (maximum . map length . words) s =                           if s !! n == ' ' || s !! n == '\t' || s !! n == '\n'        take n s ++ "\n" ++ f n (drop (n+1) s)                           else f (n - 1) s          --here once called n-1 proceeds call on or smaller n    | otherwise = error "try bigger width!" 

here example ,where to on last line should on second line:

*main> let s = "this miscellaneous items starting shitty ." *main> putstr $ f 22 s miscellaneous items starting shitty . 

any ideas?

yes, once call again f new value of n, has no way reference old value of n unless pass explicitly. 1 way have internal recursive function width parameter, have, can reference parameter outer function when needed. example, works:

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

here width current width in calculation, , n unchanged, allows f' use when resetting calculation @ start of new line.

that's answering precise question. exercise rewrite code in more idiomatic haskell, avoiding performance pitfalls overreliance on !!. first working, , make elegant!


Comments

Popular posts from this blog

javascript - Google App Script ContentService downloadAsFile not working -

javascript - Function overwritting -

php - Find a regex to take part of Email -