鑒于所有 Ints 都大于 100,我正在嘗試撰寫一個函式來查找 Ints 串列的最后一個元素。這是我到目前為止撰寫的代碼:
isLeast100All :: [Int] -> [Int]
isLeast100All list = filter (>100) list
lastList :: [Integer] -> Integer
lastList list' = case list' of
isLeast100All list
| list == [] -> 0
| list == [x] -> x
| list == [x:xs] -> lastList xs
這給了我錯誤:“模式中的決議錯誤:isLeast100All”
我覺得這里缺少一些簡單的東西,但我不確定它是什么。我的 lastList 函式基于以下定義:
lastList :: [Integer] -> Integer
lastList x = case x of
[] -> 0
[x] -> x
x:xs -> lastList xs
uj5u.com熱心網友回復:
您需要修復您的型別并使用filter而不是mapfor isLeast100All:
isLeast100All :: [Integer] -> [Integer]
isLeast100All = filter (> 100)
lastList :: [Integer] -> Integer
lastList list' = case isLeast100All list' of
[] -> 0
xs -> last xs
要不就:
lastList :: [Integer] -> Integer
lastList l = last $ 0 : filter (> 100) l
uj5u.com熱心網友回復:
你的定義有幾個問題lastList。你混淆了listand list',[x:xs]should be (x:xs),并且混合了謂詞保護和 case ... 運算式。
這是使用謂詞守衛定義它的一種方法:
lastList :: [Integer] -> Integer
lastList list' = myLast $ isLeast100All list'
myLast :: [Integer] -> Integer
myLast list
| list == [] = 0
| tail list == [] = head list
| otherwise = myLast $ tail list
這是另一個用例......:
lastList :: [Integer] -> Integer
astList list' = case isLeast100All list' of
[] -> 0
[x] -> x
(x:xs) -> lastList xs
后一個是不必要的低效,因為過濾功能isLeast100All在每個遞回級別都應用于整個剩余串列,但我的目標是使這些盡可能與您的代碼相似。
Guru Stron 的回答提供了更簡單的選擇。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/487892.html
上一篇:我怎么能操縱串列理解?
