[英]Decremented value called in the recursion in Haskell
因此,我有此功能,可將文本向左對齊給定的列寬。 我已經解決了它的一些問題,但是一旦調用它,我無法使它不使用減量的參數,而是返回到n
的起始值。 這是我的代碼:
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!"
這是一個示例,其中最后一行上的to
實際上應該在第二行上:
*Main> let s = "This miscellaneous items are starting to get shitty ."
*Main> putStr $ f 22 s
This miscellaneous
items are starting
to get shitty .
有任何想法嗎?
是的,再次使用新值n調用f時,除非顯式傳遞它,否則無法引用舊值n。 一種實現方法是,如您所願,使用內部遞歸函數及其width參數,但是可以在需要時將該參數引用到外部函數。 例如,類似的方法有效:
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!"
這里width
是計算中的當前寬度, n
始終不變,這使得f'
在新行的開頭重置計算時可以使用它。
那只是回答您的確切問題。 一個不錯的練習就是用更加慣用的Haskell重寫代碼,避免一些性能陷阱,例如對!!
的過度依賴!!
。 但是首先要使其工作,然后使其優雅!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.