Haskell代码问题说明:代码应返回数字中有多少个数字将整个数字相除。例如,12有两个数字[1,2],两个数字都除以2(12%2和12%1都为0),因此返回2,因为有两个数字对数字进行了除法。对于102,将2返回为1,将2除以102,但未定义除以0。
但是,使用此代码,我在数字中间包含0的数字时遇到错误(例如1001020)我收到“程序错误:Prelude.read:无解析”
任何帮助将不胜感激。非常感谢。
import Control.Monad
import Data.Array
import Data.Bits
import Data.Char
import Data.List
import Data.Set
import Debug.Trace
import System.Environment
import System.IO
import System.IO.Unsafe
findDigits :: Int -> Int
findDigits n = digits n n 0 (lengths n)
where
digits n on count endCheck
| endCheck == 0 = count
| header n == 0 = digits (tailer n) on count (endCheck-1)
| on `mod` header n == 0 = digits (tailer n) on (count+1) (endCheck-1)
| otherwise = digits (tailer n) on count (endCheck-1)
header :: Int -> Int
header x = digitToInt . head . show $ x
tailer :: Int -> Int
tailer x = read . tail . show $ x
lengths :: Int -> Int
lengths x = length . show $ x
我认为您正在尝试在函数中做太多事情。通常,最好使用分别解决一个简单任务的小功能,然后将它们组合到同样小的功能中,并执行(稍微)更复杂的任务。
例如,我们可以使一个函数digits :: Int -> [Int]
返回一个数字列表:
digits :: Int -> [Int]
digits x | x >= 10 = r : digits q
| otherwise = [x]
where (q,r) = quotRem x 10
例如:
Prelude> digits 102
[2,0,1]
然后我们可以过滤这些数字以检查这些数字是否不为零(因为该数字不可除),以及该数字是否可以被该数字除:
dividableDigits :: Int -> [Int]
dividableDigits n = filter (\x -> x /= 0 && mod n x == 0) (digits n)
现在,只需计算匹配的数字即可。我将其保留为练习。