[英]Applying a function to a recursively built list within the definition of the recursive function in haskell
這不是一個很好的例子,但是很容易理解我的要求。 假設我要遞歸地重建列表,然后在構建列表后對其應用sort函數。 這是一個獲得正確答案的實現,但不是我想要的方式。
import Data.List
rebuild_and_sort :: [Int] -> [Int]
rebuild_and_sort [] = []
rebuild_and_sort (b:bs) = sort (b:rebuild_and_sort bs)
問題在於將對參數列表中的每個元素調用排序。 是否有某種方法可以使排序在完全重建列表之后不更改所需參數的情況下僅調用一次?
將遞歸委托給worker函數並在頂層調用sort
import Data.List(sort)
rbsort :: [Int] -> [Int]
rbsort = sort . go
where go [] = []
go (x:xs) = x: go xs -- here you should be doing something useful
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.