简体   繁体   中英

Decremented value called in the recursion in Haskell

So, I have this function that aligns the text to the left for a given column width. I have already fixed some of its problems, but I am unable to make it not use the decremented parameter once it is called, but to return to the starting value of n . Here is my 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'
       then take n s ++ "\n" ++ f n (drop (n+1) s)                   
       else f (n - 1) s          --Here once called for some n-1 it proceeds to call it from then on only for it or even smaller n
   | otherwise = error "Try bigger width!"

Here is an example ,where the to on the last line should be really on the second line:

*Main> let s = "This miscellaneous items are starting to get shitty ."
*Main> putStr $ f 22 s
This miscellaneous
items are starting
to get shitty .

Any ideas?

Yes, once you call again f with a new value of n, it has no way to reference the old value of n unless you pass it explicitly. One way to do it is to have an internal recursive function with its width parameter, as you have, but that can reference the parameter to the outer function when needed. For example, something like that works:

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

Here width is the current width in the calculation, and n is always unchanged, which allows f' to use it when resetting the calculation at the start of a new line.

That's only answering your precise question. A good exercise would then be to rewrite your code in what would be more idiomatic Haskell, avoiding some performance pitfalls like the overreliance on !! . But first get it working, and then make it elegant!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM