簡體   English   中英

在Haskell中如何計算列表中特定Int的數量

[英]In Haskell how to count the number of a specific Int in a list

我試圖創建一個countElems一個Int和一個[Int]的函數countElems ,並返回列表中該特定Int數量。 到目前為止,我有:

countElems :: Int -> [Int] -> Int
countElems n (x:xs)
| xs == []   = 0
| n == x     = 1 + countElems n xs
| n /= x     = countElems n xs

運行時,這似乎可行,但是在進一步檢查時,如果輸入countElems 9 [5, 3, 9, 3, 9]則輸出為1而不是2 我可以看到這是因為它在查看n == x導致錯誤輸出之前會檢查xs == [] ,但是如果我調換這兩種情況,則表示Non-exhaustive pattern

經過進一步思考后編輯:

我可以消除此代碼發布的錯誤@ user2407038:

countElems :: Int -> [Int] -> Int
countElems _ [] = 0
countElems n (x:xs)
| n == x     = 1 + countElems n xs
| n /= x     = countElems n xs

看起來不太優雅,但功能相同嗎?

另一個沒有任何遞歸子句的:

countElem e = length . filter (e ==)

第一次檢查( xs == [] = 0 )時,您忘記檢查x==n是否為1而不是0

countElems n (x:xs)
| xs == []   = if x==n then 1 else 0
| n == x     = 1 + countElems n xs
| n /= x     = countElems n xs

另一個(可能更直接)的實現可能會整體上看一下列表:

cE n [] = 0
cE n (x:xs) = (if n==x then 1 else 0) + (cE n xs)

不管您按哪個順序放置警衛,您的功能都並不詳盡。考慮countElems 9 [] 這是一個錯誤,因為沒有模式匹配空列表。 (也許這是您的情況所希望的行為-但通常錯誤很嚴重)。 考慮在此處使用模式匹配:

countElems n (x:xs) = fromEnum (n == x) + countElems n xs
countElems _ []     = 0

fromEnum避免了我喜歡的fromEnum if ,但是您不必使用它。

在這里可能不需要使用顯式遞歸。 嘗試\\x = length . filter (==x) \\x = length . filter (==x)

您也可以使用map編寫它:

countElems :: Int -> [Int] -> Int
countElems n xs = sum $ map (fromEnum . (==n)) xs

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM