簡體   English   中英

計算整數 Haskell 中的奇數位數

[英]Count number of odd digits in Integer Haskell

我正在嘗試制作使用 Haskell 計算整數奇數位數的程序。 我在檢查更長的整數時遇到了問題。 我的程序現在是這樣的:

oddDigits:: Integer -> Int
x = 0
oddDigits i
   | i `elem` [1,3,5,7,9] = x + 1
   | otherwise = x + 0

例如,如果我的整數是 22334455,我的程序應該返回值 4,因為該整數中有 4 個奇數。 如何檢查該整數中的所有數字? 目前它只檢查第一位數字並返回 1 或 0。我對 haskell 還是很陌生。

為了解決此類問題,您通常會將其分解為較小的問題。 一個典型的管道是:

  1. 將數字拆分為數字列表;
  2. 過濾奇數;
  3. 計算結果列表的長度。

因此,您可以在這里實現/使用輔助函數。 例如,我們可以生成一個數字列表:

digits' :: Integral i => i -> [i]
digits' 0 = []
digits' n = r : digits' q
    where (q, r) = quotRem n 10

這里的數字將以相反的順序產生,但由於這不會影響數字的數量,所以這不是問題。 我將其他輔助函數留作練習。

您可以先將整數22334455轉換為列表"22334455" 然后找出所有滿足要求的元素。

import Data.List(intersect)

oddDigits = length . (`intersect` "13579") . show

這是一種有效的方法:

oddDigits :: Integer -> Int
oddDigits = go 0
  where
    go :: Int -> Integer -> Int
    go s 0 = s
    go s n = s `seq` go (s + fromInteger r `mod` 2) q
      where (q, r) = n `quotRem` 10

這是尾遞歸的,不會累積 thunk,也不會構建不必要的列表或其他需要垃圾收集的結構。 它還可以正確處理負數。

暫無
暫無

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

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