试图检查在haskell中对原始数字进行除法运算的数字



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)

现在的问题是计算匹配的数字。我把它留作练习。

最新更新