我想撰寫一個回傳串列最長前綴的函式,將函式應用于該前綴中的每個專案會產生一個嚴格升序的串列。
例如:
最長升序前綴 (`mod` 5) [1..10] == [1,2,3,4]
最長升序前綴奇數 [1,4,2,6,8,9,3,2,1] == [1]
longestAscendingPrefix :: Ord b => (a -> b) -> [a] -> [a]
longestAscendingPrefix _ [] = []
longestAscendingPrefix f (x:xs) = takeWhile (\y z -> f y <= f z) (x:xs)
此代碼片段在標題中生成錯誤訊息。似乎問題在于該 lambda 函式。
uj5u.com熱心網友回復:
takeWhile有型別takeWhile :: (a -> Bool) -> [a] -> [a]。因此,第一個引數是將串列的元素映射到 a 的函式Bool。您的 lambda 運算式具有 type Ord b => a -> a -> Bool,這沒有多大意義。
您可以通過以下方式使用顯式遞回:
longestAscendingPrefix :: Ord b => (a -> b) -> [a] -> [a]
longestAscendingPrefix f = go
where go [] = []
go [x] = …
go (x1:x2:xs) = …
您需要在其中填寫…最后一個對 . 進行遞回呼叫的部分go。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/409219.html
標籤:
上一篇:express和node.js中的天氣資料未在我的命令列中列印
下一篇:洗掉值后重新計算總體方差的公式
