我有两个类似于filter
和的功能takeWhile
。
filterAcc, takeWhileAcc :: ([a] -> Bool) -> [a] -> [a]
filterAcc p xs = go xs []
where go [] acc = acc
go (x:xs) acc
| p (x:acc) = go xs (x:acc)
| otherwise = go xs acc
takeWhileAcc p xs = go xs []
where go [] acc = acc
go (x:xs) acc
| p (x:acc) = go xs (x:acc)
| otherwise = acc
它们都采用谓词和列表,它们与常规的不同之处filter
在于takeWhile
谓词将累积的结果作为输入。
我的问题是,虽然filter even [1..]
会立即(懒惰地)开始产生输出,但会filterAcc (any even) [1..]
挂起。我的怀疑是辅助函数go
正在阻止这些函数懒惰地行动。
我怎样才能让这些功能懒惰地运行?